Consider using the following code instead:
$(function() {
var matches = window.location.href.match(/\?fb=([0-9]+)/i);
if (matches) {
var number = matches[1];
alert(number); // will alert 4!
}
});
Test an example of it here: http://jsfiddle.net/GLAXS/
The regular expression is only slightly modified from what you provided. The g
lobal flag was removed, as you're not going to have multiple fb=
's to match (otherwise your URL will be invalid!). The case i
nsensitive flag flag was added to match FB=
as well as fb=
.
The number is wrapped in curly brackets to denote a capturing group which is the magic which allows us to use match
.
If match
matches 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 4
is contained in the second element.