I keep trying to match the page number, but all I'm getting is undefined. What am I doing wrong?
var currentLink = "page_number=1";
var whatPage = currentLink.match(/page_number=([1-9])/g);
console.log(whatPage[1]);
I keep trying to match the page number, but all I'm getting is undefined. What am I doing wrong?
var currentLink = "page_number=1";
var whatPage = currentLink.match(/page_number=([1-9])/g);
console.log(whatPage[1]);
The problem is that you're using the /g
flag, which will return an array of all matches to that regular expression in the string (disregarding capture groups - they aren't visible in the output with /g
) - for example, if the input was page_number=1,page_number=2
it would result in page_number=2
.
var currentLink = "page_number=1,page_number=2";
var whatPage = currentLink.match(/page_number=([1-9])/g);
console.log(whatPage[1]);
To use the capturing group of the only match, just remove the global flag:
var currentLink = "page_number=1";
var whatPage = currentLink.match(/page_number=([1-9])/);
console.log(whatPage[1]);
A regex is likely overkill here. Why not just use split() like this:
var whatPage = currentLink.split('=')[1];
However, if a regex is necessary, you could utilize:
var whatPage = currentLink.match(/page_number=([1-9]+)/);
console.log(whatPage[1]);
Note, I added the +
symbol in the case that your page number isn't strictly within the range of 1-9.
Try this way
var currentLink = "page_number=1";
var whatPage = currentLink.match(/[1-9]+/);
console.log(whatPage[0]);