开发者

Whats the best way to get an id from a URL written in different ways?

开发者 https://www.devze.com 2023-03-22 10:04 出处:网络
I\'m trying to find a quick way to get an ID from a url li开发者_如何学Cke this in javascript or jquery?

I'm trying to find a quick way to get an ID from a url li开发者_如何学Cke this in javascript or jquery?

https://plus.google.com/115025207826515678661/posts
https://plus.google.com/115025207826515678661/
https://plus.google.com/115025207826515678661
http://plus.google.com/115025207826515678661/posts
http://plus.google.com/115025207826515678661/
http://plus.google.com/115025207826515678661
plus.google.com/115025207826515678661/posts
plus.google.com/115025207826515678661/
plus.google.com/115025207826515678661

want to just get 115025207826515678661 from the URL

Is there a sure way to always get the ID regardless of the way its typed?


You could use this javascript which works on all the urls you posted:

var url, patt, matches, id;

url = 'https://plus.google.com/115025207826515678661/posts';
patt = /\/(\d+)(?:\/|$)/
matches = patt.exec(url);
id = matches[1];


Use the following regular expression to extract the value:

\/([0-9]+)\/?

Tested on all of your input strings and it worked on each. The first and only group will have the number you're looking for


var pos=url.indexOf('com').
var str1=url.substr(pos+3,21);

if the 21 is not constant, then just check the indexOf('/') in the substr:

var pos=url.indexOf('com').
var str1=url.substr(pos+3);
pos=str1.indexOf('/');
var str2=str1.substr(0,pos);
alert(str2);

or, use some regexp magic as was written in a different answer here.


I believe you could create a new string, and then loop through the URL string, and copy any numbers into the new string, especially if the URLs never have other numerical characters.

Basically, stripping all but numerical characters.

0

精彩评论

暂无评论...
验证码 换一张
取 消