0

I am using the following code (with the help of this post) to remove query string parameters that contain "all"?

It turns:

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

How can I modify the code to use a variable instead of "/all/"? I want to be able to easily switch out which parameter to remove.

Existing code (working but no variable):

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();

New code (not working)

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):**

The new code gives the following error: "Uncaught TypeError: re.test is not a function"

Sam
  • 1,290
  • 3
  • 23
  • 46

1 Answers1

0

You can use RegExp constructor

let parametervariable = "somefoovariable";
let re = new RegExp(parametervariable);
guest271314
  • 1
  • 10
  • 82
  • 156
  • @Sam Are you expecting the forward slashes to be part of the `RegExp`? `/all/` is a `RegExp` literal. `new RegExp("all")` results in `/all/` – guest271314 Oct 18 '17 at 17:07