0

How do you write a JS regular expression to extract the first "2" from "/?page=2&promo_id=1234". (ie page number 2)

Thanks!

1

4 Answers 4

2

This should do the trick.

var match = /page=(\d+)/.exec("/?page=2&promo_id=1234"), pageNum = match[1];
Sign up to request clarification or add additional context in comments.

2 Comments

I wrote a solution very close to yours, but they had both the same issue: if it doesn't match (say, because there is no number), JS will try to read the 2nd element of a null-value, and crash…
that's quite context specific but || undefined at the end should work it out.
1
var extractPageNumber = function(s) {
  var r=/page=(\d+)/, m=(""+s).match(r);
  return (m) ? Number(m[1]) : undefined;
};
extractPageNumber("/?page=2&promo_id=1234"); // => 2
extractPageNumber("/?page=321&promo_id=1234"); // => 321
extractPageNumber("foobar"); // => undefined

Comments

1

It depend on what may vary in your string. If the number is the only variable, then:

var match, pageNumber;
if(pageNumber = "/?page=2&promo_id=1234".match(/page=(\d+)/))
    pageNumber = match[1];

Or the ugly (but shorter) way

var pageNumber = ("/?page=223&promo_id=a".match(/page=(\d+)/)||[,undefined])[1]

Comments

0

I wouldn't use regular expressions as such, I'd use the split method:

var str="/?page=2&promo_id=1234";

document.write(str.split("/?page=")[1][0]);

Of course this will only work for single digit numbers. You could modify it to work for all numbers using a proper regular expression.

http://jsfiddle.net/u8ZXc/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.