简体   繁体   中英

Remove query param from URL on button click not working

I want to remove a query param in the URL on button click so the link will be amended from www.example.com/?queryparam=hello to www.example.com/ .

When I try:

window.location.href.split('?')[0]; 

In the console, it returns the href minus the query param (correctly). But in actual browser test it doesn't execute the code on the actual button click.

Here is my code:

window.addEventListener('message', function(event) {
  if (window.location.href.indexOf('?queryParam=') > -1) {
    $('.button').click(function() {
      window.location.href.split('?')[0];
    });
  }
  return;
}, false);

Splitting and accessing the array doesn't mutate the original string. The reason you saw it in the console as the base URL is because it evaluates to www.example.com but you aren't changing the original window.location.href . Reassign it:

window.location.href = window.location.href.split('?')[0];

Your code:

window.location.href.split('?')[0];

Is just an expression. It evaluates to a value, it essentially has no effects. Reassigning will change the location as expected. Note that window is not needed (unless you have a local variable named location ). You could also shorten it to:

location = location.href.split('?')[0];

Or even:

location.assign(location.href.split('?')[0]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM