Regex find id in url

I have the following URL:

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

Although it could 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 other pages where there is also /product in the url, and not at the beginning of the path.

What does a regex look like?

+4
source share
3 answers
  • Use window.location.pathname to get the current path (excluding TLD).

  • Use a JavaScript match string.

  • Use regex /^\/product\/(\d+)/ to find the path starting with / product /, then one or more digits (add i to the right to maintain 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. } 
+5
source

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

+4
source

Just as an alternative, do it without regex (although I assume regex is awfully good 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
source

All Articles