Cameron
Cameron

Reputation: 28783

Replace everything after last character in URL

I have the following code which replaces the current URL using JavaScript:

window.location.replace(window.location.href.replace(/\/?$/, '#/view-0'));

However if I have a URL like:

domain.com/#/test or domain.com/#/

It will append the #/view-0 to the current hash. What I want to is replace EVERYTHING after the last part of the URL including any query strings or hashes.

So presume my regex doesn't handle that... How can I amend it, to be more aggressive?

Upvotes: 0

Views: 1050

Answers (2)

vks
vks

Reputation: 67968

(^[^\/]*?\/)(?:.*)

Use this.Replace by \1 then your string

See demo.

http://regex101.com/r/sA7pZ0/28

Upvotes: 1

VisioN
VisioN

Reputation: 145378

The following syntax may help:

location.href.replace(/[?#].*$/, '#/view')

It will replace everything after (and together with) ? or # in the string with #/view.

Upvotes: 1

Related Questions