Regex to find id in url

/\/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

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