将值附加到URL搜索参数

时间:2018-12-07 22:01:10

标签: javascript jquery

我试图在URL的搜索参数中添加一个值,但部分无法正常工作。例如,我有以下网址:

http://localhost.com/?color=Green&size=L

我现在如何添加第二个值来用,分隔颜色?

这是设置第二个参数后URL的外观:

http://localhost.com/?color=Green,Red&size=L

我已经在这里尝试过了

window.history.pushState(null, null, window.location.search + ',' + 'Red');

但是结果是:

http://localhost.com/?color=Green,Red&size=L,Red

那么如何在URL中的搜索参数中添加逗号分隔的值?

2 个答案:

答案 0 :(得分:3)

使用正则表达式匹配color=...参数。

window.history.pushState(null, null, window.location.search.replace(/\bcolor=[^&]*/, '$&,Red'));

答案 1 :(得分:0)

您可以解析网址,对其进行变异并重新构建:

  function parseURL(url) {
    const [domain, rest] = url.split("?");
    const args = {};
    for(const [k, v] of rest.split("&").map(pair => pair.split("=")))
      args[k] = v;
    return { domain, args };
 }

 const toURL = ({ url, args }) =>
    url + "?" + Object.entries(args).map(pair => pair.join("=")).join("&");

 const url = parseURL(window.location);
 url.args["color"] += ",Red";
 window.location = toURL(url);

这样,您可以轻松修改所有不同的参数。

相关问题