【问题标题】:Why does this jQuery code not work?为什么这个 jQuery 代码不起作用?
【发布时间】:2011-06-02 17:33:33
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery regex replace match


    【解决方案1】:

    考虑改用以下代码:

    $(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/

    正则表达式仅对您提供的内容稍作修改。 global 标志已被删除,因为您不会有多个 fb= 匹配(否则您的 URL 将无效!)。添加了 case insensitive 标志标志以匹配 FB= 以及 fb=

    用大括号括起来的数字表示capturing group,这是让我们可以使用match 的魔力。

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

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

    【讨论】:

    • 谢谢,请解释一下这究竟是如何工作的?比赛中的那个数组是什么?
    • 更好的方法是搜索window.location.search,这样您就不会意外匹配路径或哈希中的子字符串。
    • match 返回匹配数组。
    • @tfbox /\?fb=([0-9]+)/i 中的括号创建一个“捕获组”。与该捕获组的模式匹配的子字符串在 String.match() 返回的数组中可用。索引 0 是整个匹配的字符串,1..N 是匹配每个捕获组的子字符串。
    【解决方案2】:

    如果您只需要获取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
        }
    

    【讨论】:

      【解决方案3】:

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


      我有一半的心思提供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")
      

      【讨论】:

        【解决方案4】:

        使用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'));
        

        【讨论】:

        • 我对正则表达式非常陌生,今天才弄脏了它,所以看着那里的代码,我根本不知道如何实现它,哈哈。
        【解决方案5】:

        如果您是 Regex 的新手,不妨试试Program that illustrates the ins and outs of Regular Expressions

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-05
        • 2012-02-22
        相关资源
        最近更新 更多