2

How to remove parameters with value = 3 from URL string?

Example URL string:

https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3 
mr.boris
  • 3,667
  • 8
  • 37
  • 70

3 Answers3

2

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&param2=3&param3=2&param4=1&param5=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)
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
  • Thanks! I think it is better than regular expression. – mr.boris Aug 23 '18 at 02:10
  • @mr.boris see updated example, iterating over it and deleting at the same time will cause it to skip entries so you have to make a clone first and loop over the clone to prevent this problem (it is similar to iterating over [arrays and deleting](https://stackoverflow.com/questions/9882284/looping-through-array-and-removing-items-without-breaking-for-loop)) – Patrick Evans Aug 23 '18 at 02:44
1

You could use a regular expression replace. Split off the query string and then .replace &s (or the initial ^) up until =3s:

const str = 'https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3';
const [base, qs] = str.split('?');
const replacedQs = qs.replace(/(^|&)[^=]+=3\b/g, '');
const output = base + (replacedQs ? '?' + replacedQs : '');
console.log(output);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

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&param2=3&param3=2&param4=1&param5=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);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360