JavaScript:从URL搜索参数中删除值

Mr.*_* Jo 1 javascript

我在这里有这个URL:

http://localhost.com/?color=Red,Blue,Green
Run Code Online (Sandbox Code Playgroud)

URL也可以采用以下格式:

http://localhost.com/?color=Red,Green,Blue
Run Code Online (Sandbox Code Playgroud)

我现在正在尝试Green从URL中删除值,包括,它是否充当分隔符.我在这里试过这个RegExp:

var name = 'Green';
var re = new RegExp('(' + name + ',|' + name + ')');
var newUrl = window.location.search.replace(re, '');
window.history.pushState(null, null, newUrl);
Run Code Online (Sandbox Code Playgroud)

所以我想说的是,删除Green,或者Green如果Green,找不到,将使用第二次检查.但是当我运行它时,URL看起来像这样:

http://localhost.com/?olor=Red,Green,Blue
Run Code Online (Sandbox Code Playgroud)

c从完全奇怪的颜色中删除了它.我已经RegExp在一个工具中测试了我的在线并且选择了文本但是在这里它不起作用.我又做错了什么?

更新

这是与Brunos答案的尝试,但正如你所看到的,有时它不会:

function replaceColor(search, name) {
  var reS = new RegExp(`=${name}(,|$)`);
  var reM = new RegExp(`,${name},`);
  var reE = new RegExp(`\b${name}$`);
  return search
    .replace(reS, '=')
    .replace(reM, ',')
    .replace(reE, '')
    .replace(/,$/, '')
}

alert(replaceColor('?size=K,M,S&color=Green,Red,Black', 'Red')) //Works

alert(replaceColor('?size=K,M,S&color=Green,Red,Black', 'Green')) //Works

alert(replaceColor('?size=K,M,S&color=Green,Red,Black', 'Black')) //Don't works
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

Tyl*_*per 5

为什么你的例子不起作用:

您的正则表达式查找green或者green,在您的第一个示例中查找URL包含,green.因为你只替换green它的一部分,结果是一个尾随的逗号:red,blue,.

c从完全奇怪的颜色中删除了它.

我在你的例子中看不到任何可以证明这种行为的东西.我认为这与您提供的代码无关.

var name = 'Green';
var re = new RegExp('(' + name + ',|' + name + ')');
var newUrl = "http://localhost.com/?color=Red,Blue,Green".replace(re, '');
console.log(newUrl);
Run Code Online (Sandbox Code Playgroud)


由于Bruno似乎已经介绍了Regex解决方案,我将为您提供一些替代方案.

运用 URLSearchParams

您可以使用URLSearchParams, split()将值转换为数组,filter()输出green,然后将join()它们重新组合在一起.

const urlParams = new URLSearchParams(window.location.search);
const colors = urlParams.get('color');

let result = colors.split(",").filter(n => n != "green").join(",");
Run Code Online (Sandbox Code Playgroud)

如果您需要支持Internet Explorer,可以参考此答案,其中包括以下方法来检索URL参数 - 该result部分可以保持不变:

function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

var colors = gerParameterByName("color"); 
var result = colors.split(",").filter(n => n != "green").join(",");
Run Code Online (Sandbox Code Playgroud)