繁体   English   中英

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

[英]Why does this jQuery code not work?

为什么以下 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然后只检索号码?

请考虑改用以下代码:

$(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=匹配(否则您的 URL 将无效。)。 添加了不区分i标志标志以匹配FB=以及fb=

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

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

在我们运行的示例中,字符串“?fb=4”被匹配,返回数组的第一个值也是如此。 我们定义的唯一捕获组是数字匹配器; 这就是为什么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
    }

如何使用下面的 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'));

那么,您想提供一个查询字符串,然后根据参数获取它的值吗?


我有一半的心思在 JavaScript 中提供 Get 查询字符串值

但后来我看到一个小孩滥用了一个非常尊重的 Stack Overflow 答案

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

当您使用它时,只需像这样调用 function。

getParameterByName("fb")

如果您是 Regex 的新手,为什么不尝试说明正则表达式来龙去脉的程序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM