Reputation: 21877
How do you write a JS regular expression to extract the first "2" from "/?page=2&promo_id=1234
". (ie page number 2)
Thanks!
Upvotes: 0
Views: 106
Reputation: 1590
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]
Upvotes: 1
Reputation: 156384
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
Upvotes: 1
Reputation: 10047
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.
Upvotes: 0
Reputation: 4820
This should do the trick.
var match = /page=(\d+)/.exec("/?page=2&promo_id=1234"), pageNum = match[1];
Upvotes: 2