How to remove parameters with value = 3
from URL string?
Example URL string:
https://www.example.com/test/index.html?param1=4¶m2=3¶m3=2¶m4=1¶m5=3
How to remove parameters with value = 3
from URL string?
Example URL string:
https://www.example.com/test/index.html?param1=4¶m2=3¶m3=2¶m4=1¶m5=3
If you are targeting browsers that support URL and URLSearchParams you can loop over the URL's searchParams
object, check each parameter's value, and delete() as necessary. Finally using URL's href
property to get the final url.
var url = new URL(`https://www.example.com/test/index.html?param1=4¶m2=3¶m3=2¶m4=1¶m5=3`)
//need a clone of the searchParams
//otherwise looping while iterating over
//it will cause problems
var params = new URLSearchParams(url.searchParams.toString());
for(let param of params){
if(param[1]==3){
url.searchParams.delete(param[0]);
}
}
console.log(url.href)
You could use a regular expression replace
. Split off the query string and then .replace
&
s (or the initial ^
) up until =3
s:
const str = 'https://www.example.com/test/index.html?param1=4¶m2=3¶m3=2¶m4=1¶m5=3';
const [base, qs] = str.split('?');
const replacedQs = qs.replace(/(^|&)[^=]+=3\b/g, '');
const output = base + (replacedQs ? '?' + replacedQs : '');
console.log(output);
There is a way to do this with a single regex, using some magic, but I believe that would require using lookbehinds, which most JavaScript regex engines mostly don't yet support. As an alternative, we can try splitting the query string, then just examining each component to see if the value be 3
. If so, then we remove that query parameter.
var url = "https://www.example.com/test/index.html?param1=4¶m2=3¶m3=2¶m4=1¶m5=3";
var parts = url.split(/\?/);
var params = parts[1].replace(/^.*\?/, "").split(/&/);
var param_out = "";
params.forEach(function(x){
if (!/.*=3$/.test(x))
param_out += x;
});
url = parts[0] + (param_out !== "" ? "?" + param_out : "");
console.log(url);