【问题标题】:Regular expression to find and replace specific value from a URL从 URL 中查找和替换特定值的正则表达式
【发布时间】:2013-11-20 05:24:51
【问题描述】:

我正在尝试从 URL 中提取 ?ref 值并希望将其替换为其他值。

例如,假设我的 URL 类似于 http://myexample.com/?ref=test?nref=xml&page=1 或者它可以是 http://myexample.com/?fref=like?ref=test?nref=xml&page=1

从上面的 url 我想找到 ?ref 值并想用另一个字符串替换它,比如“testing”。任何帮助,也想学习高级正则表达式任何帮助。

提前致谢。

【问题讨论】:

标签: javascript jquery regex expression


【解决方案1】:

您发布的示例的解决方案。

str = str.replace(/\b(ref=)[^&?]*/i, '$1testing');

正则表达式:

\b             the boundary between a word char (\w) and and not a word char
 (             group and capture to \1:
  ref=         'ref='
 )             end of \1
[^&?]*         any character except: '&', '?' (0 or more times)

i 修饰符用于不区分大小写的匹配。

working demo

【讨论】:

    【解决方案2】:

    确保您没有两个“?”在网址中。我假设你的意思是 http://myexample.com?ref=test&nref=xml&page=1

    你可以使用下面的函数

    这里 url 是你的 url,name 是键,在你的例子中是“ref”,new_value 是新值,即替换“test”的值

    函数将返回新的 url

    function replaceURLParam (url, name, new_value) {
    
      // ? or &, name=, anything that is not &, zero or more times          
      var str_exp = "[\?&]" + name + "=[^&]{0,}";
    
      var reExp = new RegExp (str_exp, "");
    
      if (reExp.exec (url) == null) {  // parameter not found
          var q_or_a = (url.indexOf ("?") == -1) ? "?" : "&";  // ? or &, if url has ?, use &
          return url + q_or_a + name + "=" + new_value;
      }
    
      var found_string = reExp.exec (url) [0];
    
      // found_string.substring (0, 1) is ? or &
      return url.replace (reExp, found_string.substring (0, 1) + name + "=" + new_value);
    }
    

    【讨论】:

      【解决方案3】:

      试试这个:

      var name = 'ref', 
          value = 'testing',
          url;
      
      url = location.href.replace(
          new RegExp('(\\?|&)(' + name + '=)[^&]*'), 
          '$1$2' + value
      );
      

      new RegExp('(\\?|&)(' + name + '=)[^&]*') 给出/(\?|&)(ref=)[^&]*/ 这意味着:

      "?" or "&" then "ref=" then "everything but '&' zero or more times".
      

      最后,$1 持有(\?|&) 的结果,而$2 持有(ref=) 的结果。

      阅读链接:replaceregexp

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-20
        • 1970-01-01
        • 1970-01-01
        • 2015-03-25
        • 2011-06-16
        • 1970-01-01
        • 2017-01-28
        相关资源
        最近更新 更多