Regex to find id in url

点点圈 提交于 2020-01-03 08:50:11

问题


I have the following URL:

http://example.com/product/1/something/another-thing

Although it can also be:

http://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?


回答1:


  1. Use window.location.pathname to retrieve the current path (excluding TLD).

  2. Use the JavaScript string match method.

  3. Use the regex /^\/product\/(\d+)/ to find a path which starts with /product/, then one or more digits (add i right at the end to support case insensitivity).

  4. 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.
    }
    



回答2:


/\/product\/(\d+)/ and obtain $1.




回答3:


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



回答4:


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!



来源:https://stackoverflow.com/questions/6117501/regex-to-find-id-in-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!