1

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
daryl
  • 14,307
  • 21
  • 67
  • 92

5 Answers5

5

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 global flag was removed, as you're not going to have multiple fb='s to match (otherwise your URL will be invalid!). The case insensitive 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.

Matt
  • 74,352
  • 26
  • 153
  • 180
  • Thanks, care to explain how this works exactly? What's that array on the matches? – daryl Jun 02 '11 at 17:43
  • An even better way would be to search on `window.location.search` so you don't accidentally match substrings in the path or in the hash. – digitalbath Jun 02 '11 at 17:44
  • `match` returns an array of matches. – circusbred Jun 02 '11 at 17:47
  • @tfbox the parenthesis in `/\?fb=([0-9]+)/i` create a "capturing group". The substring that matches the pattern of that capturing group is available in the array that String.match() returns. Index 0 is the entire matched string, and 1..N are the substrings that matched each capturing group. – digitalbath Jun 02 '11 at 17:47
4

If you all you need is to grab the value of fb, just use capturing parenthesis:

    var regex = /\?fb=([0-9]+)/g; 
    var input = window.location.href;

    var tokens = regex.exec(input);

    if (tokens) { // there's a match
        alert(tokens[1]); // grab first captured token
    }
Ates Goral
  • 137,716
  • 26
  • 137
  • 190
2

How about using the following function to read the query string parameter in JavaScript:

function getQuerystring(key, default_) {
    if (default_==null)
        default_="";
    key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if(qs == null)
        return default_;
    else
        return qs[1];
}

and then:

alert(getQuerystring('fb'));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I'm seriously new to regex, only got my fingers dirty with it today so looking at that code there I have no idea how to implement it at all lol. – daryl Jun 02 '11 at 17:41
2

So, you want to feed a querystring and then get its value based on parameters?


I had had half a mind to offer Get query string values in JavaScript.

But then I saw a small kid abusing a much respectful Stack Overflow answer.

// Revised, cooler.
function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)')
                    .exec(window.location.search);
    return match ?
        decodeURIComponent(match[1].replace(/\+/g, ' '))
        : null;
}

And while you are at it, just call the function like this.

getParameterByName("fb")
Community
  • 1
  • 1
naveen
  • 53,448
  • 46
  • 161
  • 251
-3

If you are new to Regex, why not try Program that illustrates the ins and outs of Regular Expressions

Jon
  • 173
  • 1
  • 4
  • 13
  • 1
    JSLint doesn't handle jQuery: http://stackoverflow.com/questions/505251/what-good-is-jslint-if-jquery-fails-the-validation – Ben Jun 02 '11 at 17:43
  • 1
    Thanks Ben, I didn't know that actually. I will use these resources from now on before I answer. – Jon Jun 02 '11 at 17:50
  • 1
    I partially lied... turns out if you are running Lint locally, jQuery core will actually pass Lint: http://docs.jquery.com/JQuery_Core_Style_Guidelines#JSLint – Ben Jun 02 '11 at 17:57