Regex to find id in url

15,053

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

Solution 2

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

Solution 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
Share:
15,053
PeeHaa
Author by

PeeHaa

So long SO main o/ and thanks for all the fish Check out my personal website or check out one of the open source projects I'm currently working on: Jeeves - A headless chatbot for the PHP room GitHub Minifine - JS and CSS minifier GitHub Requestable - online webservice for testing and debugging HTTP / REST requests GitHub OpCacheGUI - a nice webinterface for PHP's OpCache GitHub EmailTester - an online emailaddress validation regex tester GitHub Commentar - an open source PHP5.4+ commenting system GitHub HexDump - an online hex viewer GitHub RichUploader - a private filehoster GitHub PHP OAuth library GitHub Proposal for the new beginners tutorial on php.net GitHub I've created a close-voting Chrome plugin available at GitHub to help clean up Stack Overflow. If you would like to see what other projects I'm working on please visit my GitHub or drop me a line in the PHP chat.

Updated on June 18, 2022

Comments