Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript how to switch pathname of window.location property and redirect

I want to redirect a user from varying urls to a specific one. I've tried various flavors of replacing and I cant seem to get the behavior I want. This code works except I'm providing the hostname. I want to use the existing hostname from windows.location.hostname and just provide a new pathname. Sometimes the urls vary in size and slashes ('/').

window.location = 'http://localhost:36065/NewPath';

How would I change these urls?

http://somesite.com/xxx/yyy/zzz to http://somesite.com/NewPath
http://somesite.com/xxx/yyy to http://somesite.com/NewPath
http://somesite.com/xxx to http://somesite.com/NewPath

I think you get the point. The path can vary in paths, I want to replace everything after .com basically with 'NewPath'

I'd like a clean regex solution if possible but I am quite the rookie in that dept. Thanks for any tips or tricks.

like image 587
Hcabnettek Avatar asked Oct 13 '11 16:10

Hcabnettek


People also ask

How do I change the URL of a Windows location?

location = "https://www.example.com"; // Sets the new href (URL) for the current window. window. location. href = "https://www.example.com"; // Assigns a new URL to the current window.

Why is the location replace () method preferred over the location assign () method?

The replace() method of the Location interface replaces the current resource with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session History , meaning the user won't be able to use the back button to navigate to it.

What's the difference between window location and document location in JavaScript?

The window. location is read/write on all compliant browsers. The document. location is read-only in Internet Explorer but read/write in Firefox, SeaMonkey that are Gecko-based browsers.


1 Answers

location.pathname = '/newpath.html'
like image 66
Jason Harwig Avatar answered Oct 27 '22 00:10

Jason Harwig