I try to remove a part of my url in the addressbar of the browser via javascript.
but I don't understand why it's not working, if I test it in the console the result is correct but it still does not change in the address bar.
How can I do it?
url I have:http://localhost:8090/Home/Index?x=72482&success=itsdone
url I want is:
http://localhost:8888/Home/Index?x=72482
here is my javascript code:
window.location.href.replace('&', '#');
window.location.hash = "";
replace
doesn't change the string on which you call it (strings are immutable), it returns a new one.
To replace &
with #
, do
window.location = window.location.href.replace('&', '#');
If you want to remove everything from the first &
, the best is to use a regular expression :
window.location = window.location.replace(/&.*$/,'');
If what you want is to retain the x
parameter, then you should rebuild the location to ensure it's still OK if the parameters are in a different order in the URL :
window.location = window.location.replace(/([^?]*).*(\?|&)(x=)([^&]+).*/, "$1?$3$4")
This changes
"http://localhost:8888/Home/Index?a=2&x=72482&c=3"
or
"http://localhost:8888/Home/Index?x=72482&success=itsdone"
into
"http://localhost:8888/Home/Index?x=72482"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With