How do you write a JS regular expression to extract the first "2" from "/?page=2&promo_id=1234". (ie page number 2)
Thanks!
How do you write a JS regular expression to extract the first "2" from "/?page=2&promo_id=1234". (ie page number 2)
Thanks!
This should do the trick.
var match = /page=(\d+)/.exec("/?page=2&promo_id=1234"), pageNum = match[1];
|| undefined at the end should work it out.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]
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.