根据变量参数值删除查询字符串的一部分

时间:2017-10-18 16:53:08

标签: javascript regex query-string

我使用以下代码(在此post的帮助下)删除包含“all”的查询字符串参数?

转过来:

https://www.foobar.com/page?year=all&language=all&gender=femalehttps://www.foobar.com/page?gender=female

如何修改代码以使用变量而不是“/ all /”?我希望能够轻松切换出要删除的参数。

现有代码(工作但无变量):

let src = "https://www.foobar.com/page?year=all&language=all&gender=female";
let url = new URL(src);
let re = /all/;
let props = [...new URLSearchParams(url.search)]
            .filter(([key, prop]) => !re.test(prop));
url = url.origin + url.pathname;
let params = new URLSearchParams();
props.forEach(([key, prop]) => params.set(key, prop));
url += "?" + params.toString();

新代码(不工作)

let parametervariable = "/somefoovariable/";
let src = "https://www.foobar.com/page?year=all&language=all&gender=female";
let url = new URL(src);
let re = parametervariable;
let props = [...new URLSearchParams(url.search)]
            .filter(([key, prop]) => !re.test(prop));
url = url.origin + url.pathname;
let params = new URLSearchParams();
props.forEach(([key, prop]) => params.set(key, prop));
url += "?" + params.toString();
 variable):**

新代码出现以下错误:“未捕获的TypeError:re.test不是函数”

1 个答案:

答案 0 :(得分:0)

您可以使用RegExp构造函数

let parametervariable = "somefoovariable";
let re = new RegExp(parametervariable);