1

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>

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

3 Comments

I see that the return has a parsed.protocol + '//' + parsed.host + parsed.pathname. Seems like this only applies to localhost? what if I have a live website?
@frankfurt It will work for any valid URL.
Ah i see... i tried to remove all parameters from this url http://localhost:8088/products/10?param1=key1&param2=key2&param3=key3&param4=key4, but still there is "?" at the end of the pathname http://localhost:8088/products/10?. what if all parameters remove "?" also gone? so that the url looks nice like this http://localhost:8088/products/10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.