frankfurt
frankfurt

Reputation: 153

How to remove multiple parameter url using javascript?

I'm creating a function to remove more than 1 parameters without reloading with replaceState. I have created a function below, and this function works but only for 1 parameter.

If on another page I have more than 1 parameter that I want to remove, how do I do that? I want this functionality to work for all pages. Can anyone help me?

function removeURLParameter(url, parameter) {
    var urlparts = url.split('?');  
 
    if (urlparts.length >= 2) {

       var prefix = encodeURIComponent(parameter) + '=';
       var pars = urlparts[1].split(/[&;]/g);

       for (var i = pars.length; i-- > 0;) {    
          if (pars[i].lastIndexOf(prefix, 0) !== -1) {  
             pars.splice(i, 1);
          }
       }

       return urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : '');
    }
    return url;
}

$(document).ready(function(){
  const url = "http://localhost:8088/products/10?param1=key1&param2=key2&param3=key3&param4=key4"
  const removeURLParams = removeURLParameter( url, 'param3')
  
  console.log(url)
  console.log(removeURLParams)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Views: 1139

Answers (1)

Spectric
Spectric

Reputation: 31987

Here's a much simpler approach:

You can use rest parameters to allow your function to accept multiple parameters.

To remove the parameters, you can first parse the URL with the URL constructor, then get its searchParams property. Then, loop through each parameter and use URLSearchParams.delete to delete the parameter.

function removeURLParameters(url, ...parameters) {
    const parsed = new URL(url);
    parameters.forEach(e => parsed.searchParams.delete(e))
    return parsed.toString()
}

const url = "http://localhost:8088/products/10?param1=key1&param2=key2&param3=key3&param4=key4"

const res = removeURLParameters(url, 'param1', 'param3')

console.log(res)

Upvotes: 1

Related Questions