Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove some part of the URL in the address bar of the browser

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 = "";
like image 812
user2232273 Avatar asked Jan 09 '14 15:01

user2232273


1 Answers

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"
like image 53
Denys Séguret Avatar answered Oct 04 '22 18:10

Denys Séguret