为什么这个jQuery代码不起作用?

dar*_*ryl 1 javascript regex jquery replace match

为什么以下jQuery代码不起作用?

$(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?
});
Run Code Online (Sandbox Code Playgroud)

基本上我有这样的链接:

http://foo.com/?fb=4
Run Code Online (Sandbox Code Playgroud)

我如何首先找到?fb=4然后只检索号码?

Mat*_*att 5

请考虑使用以下代码:

$(function() {
    var matches = window.location.href.match(/\?fb=([0-9]+)/i);

    if (matches) {
        var number = matches[1];
        alert(number); // will alert 4!
    }
});
Run Code Online (Sandbox Code Playgroud)

在这里测试一个例子:http://jsfiddle.net/GLAXS/

正则表达式仅根据您提供的内容略微修改.g已删除了该标志,因为您不会有多个fb=匹配(否则您的网址将无效!).此案i加入nsensitive旗旗匹配FB=以及fb=.

数字用大括号括起来表示一个允许我们使用的魔法捕获组match.

如果match匹配我们指定的正则表达式,它将返回第一个数组元素中的匹配字符串.其余元素包含我们定义的每个捕获组的值.

在我们的运行示例中,字符串"?fb = 4"是匹配的,因此返回数组的第一个值.我们定义的唯一捕获组是数字匹配器; 这就是为什么4包含在第二个元素中.