2011-06-02 60 views
1

为什么不能使用以下jQuery代码?为什么这个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? 
}); 

基本上我有一个像这样的链接:

http://foo.com/?fb=4 

如何首先找到?fb=4,然后才捡回多少?

回答

5

考虑使用下面的代码代替:

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

    if (matches) { 
     var number = matches[1]; 
     alert(number); // will alert 4! 
    } 
}); 

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

正则表达式只是稍微从你提供了什么修改。 g lobal国旗已被移除,因为您不会有多个fb=匹配(否则您的网址将无效!)。案例i非敏感标志标志被添加以匹配FB=以及fb=

该数字用大括号表示,表示capturing group,这是允许我们使用match的魔法。

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

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

+0

谢谢,小心解释这是如何工作的?比赛中的阵列是什么? – daryl 2011-06-02 17:43:02

+0

更好的方法是在'window.location.search'上搜索,以免偶尔在路径或哈希中匹配子字符串。 – digitalbath 2011-06-02 17:44:07

+0

'match'返回匹配数组。 – circusbred 2011-06-02 17:47:03

-3

如果你是新的正则表达式,为什么不尝试Program that illustrates the ins and outs of Regular Expressions

+1

http://screensnapr.com/v/JpjYtU.png – daryl 2011-06-02 17:39:48

+1

JSLint不处理jQuery:http:// stackoverflow。com/questions/505251/what-good-is-jslint-if-jquery-fails-the-validation – Ben 2011-06-02 17:43:27

+1

谢谢Ben,我其实并不知道。在我回答之前,我将从现在开始使用这些资源。 – Jon 2011-06-02 17:50:14

2

如何使用following function阅读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]; 
} 

然后:

alert(getQuerystring('fb')); 
+0

我对于正则表达式非常陌生,今天只是弄脏了我的手指,所以看着那里的代码,我不知道如何实现它在所有的大声笑。 – daryl 2011-06-02 17:41:31

4

如果你需要的是抢的fb值,只需使用捕捉括号:

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 
    } 
2

所以,你要养活一个查询字符串,然后获取根据参数它的价值?


我不得不有点想提供Get query string values in JavaScript

但后来我看到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; 
} 

虽然你在它,只是调用这样的功能。

getParameterByName("fb") 
相关问题