Regex to find id in url
I have the following URL:
http://example.com/product/1/something/another-thing
Although it can also be:
开发者_如何学Chttp://test.example.com/product/1/something/another-thing
or
http://completelydifferentdomain.tdl/product/1/something/another-thing
And I want to get the number 1 (id) from the URL using Javascript.
The only thing that would always be the same is /product
. But I have some other pages where there is also /product
in the url just not at the start of the path.
What would the regex look like?
Use
window.location.pathname
to retrieve the current path (excluding TLD).Use the JavaScript string
match
method.Use the regex
/^\/product\/(\d+)/
to find a path which starts with /product/, then one or more digits (addi
right at the end to support case insensitivity).Come up with something like this:
var res = window.location.pathname.match(/^\/product\/(\d+)/); if (res.length == 2) { // use res[1] to get the id. }
/\/product\/(\d+)/
and obtain $1
.
Just, as an alternative, to do this without Regex (though i admit regex is awfully nice here)
var url = "http://test.example.com//mypage/1/test/test//test";
var newurl = url.replace("http://","").split("/");
for(i=0;i<newurl.length;i++) {
if(newurl[i] == "") {
newurl.splice(i,1); //this for loop takes care of situatiosn where there may be a // or /// instead of a /
}
}
alert(newurl[2]); //returns 1
I would like to suggest another option.
.match(/\/(\d+)+[\/]?/g)
This would return all matches of id's present.
Example:
var url = 'http://localhost:4000/#/trees/8/detail/3';
// with slashes
var ids = url.match(/\/(\d+)+[\/]?/g);
console.log(ids);
//without slashes
ids = url.match(/\/(\d+)+[\/]?/g).map(id => id.replace(/\//g, ''));
console.log(ids);
This way, your URL doesn't even matter, it justs retrieves all parts that are number only.
To just get the first result you could remove the g
modifier:
.match(/\/(\d+)+[\/]?/)
var url = 'http://localhost:4000/#/trees/8';
var id = url.match(/\/(\d+)+[\/]?/);
//With and without slashes
console.log(id);
The id without slashes would be in the second element because this is the first group found in the full match.
Hope this helps people. Cheers!
精彩评论