11

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.

Hcabnettek
  • 12,678
  • 38
  • 124
  • 190

3 Answers3

30
location.pathname = '/newpath.html'
Jason Harwig
  • 43,743
  • 5
  • 43
  • 44
  • 1
    Also a note, this keeps the hash in the URL, but that's probably not a problem. – Alex Turpin Oct 13 '11 at 16:43
  • Not quite sure how I missed this. So simple. Thanks! – Hcabnettek Oct 20 '11 at 16:12
  • @vsync, By setting the `pathname` property you maintain query params and fragment identifiers. – Jason Harwig Jun 11 '14 at 19:58
  • @JasonHarwig - just tried changing the pathname and it **didn't** maintain query params.. (FF30/WIN7) – vsync Jun 12 '14 at 08:49
  • is there a way to change the pathname so that the browser doesn't "load" the new pathname? I know there is `pushState()` but i'm trying to effectively remove the most recent url from the browser history and `pushState()` doesn't do this. – user1063287 Aug 22 '18 at 09:59
  • @user1063287 I believe the [`History.replaceState()`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) method would help here. – Anthony Walsh Feb 09 '20 at 09:49
4

You could always use the various location properties to recreate the part you need and append the new part to it:

window.location = location.protocol + "//" + location.hostname + "/NewPath";
Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
0

Just to show the hard way:

// Find everything up to the first slash and save it in a backreference
regexp = /(\w+:\/\/[^\/]+)\/.*/;

// Replace the href with the backreference and the new uri
newurl = windows.location.href.replace(regexp, "$1/dir/foo/bar/newpage.html");
Scott A
  • 7,745
  • 3
  • 33
  • 46