Why doesn’t the following jQuery code work?
$(function() {
var regex = /\?fb=[0-9]+/g;
var input = window.location.href;
var scrape = input.match(regex); // returns ?fb=4
var numeral = /\?fb=/g;
scrape.replace(numeral,'');
alert(scrape); // Should alert the number?
});
Basically I have a link like this:
http://foo.com/?fb=4
How do I first locate the ?fb=4 and then retrieve the number only?
Consider using the following code instead:
Test an example of it here: http://jsfiddle.net/GLAXS/
The regular expression is only slightly modified from what you provided. The
global flag was removed, as you’re not going to have multiplefb=‘s to match (otherwise your URL will be invalid!). The caseinsensitive flag flag was added to matchFB=as well asfb=.The number is wrapped in curly brackets to denote a capturing group which is the magic which allows us to use
match.If
matchmatches the regular expression we specify, it’ll return the matched string in the first array element. The remaining elements contain the value of each capturing group we define.In our running example, the string “?fb=4” is matched and so is the first value of the returned array. The only capturing group we have defined is the number matcher; which is why
4is contained in the second element.