【问题标题】:Javascript regex - remove variable from url if existJavascript 正则表达式 - 如果存在,则从 url 中删除变量
【发布时间】:2014-01-17 06:11:34
【问题描述】:

我有这个网址:http://localhost/example/product/illimani/?lang=fr?lang=fr

现在我想删除这个?lang=fr,因为它已经存在于 url。

希望你能理解我的问题。

如果已经存在,请移除 ?lang=fr 否则不要。

【问题讨论】:

  • 从另一个页面到达那里,您应该找到它的来源并在更改页面之前使用条件检查它是否会重复。

标签: javascript jquery regex query-string str-replace


【解决方案1】:

你可以使用:

url.replace(/(\?lang=fr)+/g, '?lang=fr')

用一个替换多个出现的?lang=fr

【讨论】:

  • 我在哪里传递我的 url 字符串?
  • 如果两次出现之间有什么东西,这不会替换字符串。
  • @Aashray - 是的。我没有考虑过这种可能性。 :)
【解决方案2】:

你可以使用类似的东西

 var re = /(\?[\w|=]*)+\1/; 
var str = 'http://localhost/example/product/illimani/?lang=fr?lang=fr?lang=fr';

str.match(re);

应该修剪re 以包含更通用格式的 URL 参数。这只会替换连续的重复项。如果您想找到不连贯的重复项,那么您应该使用编程语言恕我直言。然后您可以将其替换为特殊代码$1 backreference

【讨论】:

    【解决方案3】:

    如果你只想处理你描述的一个场景,你可以做一个简单的替换:

    var new_url = url.replace(/(\?lang=fr)+/g, '?lang=fr');
    

    要处理所有重复的变量,请尝试以下操作:

    var new_url = url;
    var temp = '';
    while( temp != new_url) { // need this in case params are out of order
        temp = new_url;
        new_url = temp.replace(/([&?])([^=&?]+=[^=&?]+)(.*)\2/g, '$1$2$3');
    }
    new_url = new_url.replace(/[&?]+/g, '&').replace(/&+/, '?').replace(/&$/, '');
    

    例如,这会将http://localhost/example/product/illimani/?foo=bar&lang=fr?foo=bar&lang=fr 变成http://localhost/example/product/illimani/?foo=bar&lang=fr

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 2017-02-27
      相关资源
      最近更新 更多