0

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]);
frosty
  • 2,559
  • 8
  • 37
  • 73
  • If you're trying to get parameter values from a URL, rather than writing an individual RegEx for each and every expected parameter, consider using something like [`searchParams`](https://stackoverflow.com/a/979995/2026606) instead. – Tyler Roper Jan 03 '19 at 04:35

3 Answers3

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]);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • It's worth noting that unless you know the page number is strictly 1-9, then you may want to append the `+` symbol to the end of your regex (i.e. `currentLink.match(/page_number=([1-9]+)/);` to cover any number of digits. – Ben Jan 03 '19 at 04:40
0

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.

Ben
  • 2,441
  • 1
  • 12
  • 16
0

Try this way

var currentLink = "page_number=1";
var whatPage = currentLink.match(/[1-9]+/);  
 console.log(whatPage[0]);
Ethan
  • 29
  • 1