Search code examples
jqueryregexurlsegment

Why is my regex not working?


I need to match any number that comes after /page/ in a URL.

Example URL:

http://example.com/something/page/2/

What i want out of it:

2

I wrote this, but for some reason i'm getting NULL.

/page/(\d)

Am i missing something? The regex i wrote works when testing it on this site, but i can't get it to work in js.

When i run this:

console.log(url);
var mr =  url.match('/page/(\d)');
console.log(mr);

I get:

http://example.com/something/page/2/ theme.js:32
null 

Any ideas?


Solution

  • You may use

    var nb = url.match(/\/page\/(\d)/)[1];
    

    When you have a / in a regexp, it needs to be escaped.

    Note that I prefer to use the /someregexp/ notation, as a literal regexp doesn't need to be computed each time it is used.