使用jQuery从URL获取ID

wes*_*bos 27 javascript jquery

我有这样的网址:

http://www.site.com/234234234
Run Code Online (Sandbox Code Playgroud)

我之后需要抓住Id /,所以在这种情况下234234234

我怎么能这么容易?

Bal*_*usC 48

获取最后一个索引后的子字符串. /

var url = 'http://www.site.com/234234234';
var id = url.substring(url.lastIndexOf('/') + 1);
alert(id); // 234234234
Run Code Online (Sandbox Code Playgroud)

它只是基本的JavaScript,不涉及jQuery.

  • 这很棒!但是,如果网址的右侧有网址,该怎么办? (3认同)

Roh*_*rbs 44

var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('/') + 1);
Run Code Online (Sandbox Code Playgroud)


Fre*_*man 10

var full_url = document.URL; // Get current url
var url_array = full_url.split('/') // Split the string into an array with / as separator
var last_segment = url_array[url_array.length-1];  // Get the last part of the array (-1)
alert( last_segment ); // Alert last segment
Run Code Online (Sandbox Code Playgroud)


Joh*_*ler 6

var url = "http://www.site.com/234234234"
var stuff = url.split('/');
var id = stuff[stuff.length-1];
//id = 234234234
Run Code Online (Sandbox Code Playgroud)


小智 6

const url = "http://www.example.com/1234"
const id = url.split('/').pop();
Run Code Online (Sandbox Code Playgroud)

试试这个,容易多了

输出给出 1234


Sim*_*mes 5

你可以用window.location.hash它来获取 id。

var id = window.location.hash;
Run Code Online (Sandbox Code Playgroud)

我认为您不需要那么多代码来实现这一点。