简体   繁体   中英

Redirect URL using javascript

is it possible to redirect the hostname of the URL using javascript?

If URL contains "content/articles", it should remain in the same URL. Otherwise, it should redirect all other URLs from www to www1.

I think i got the "/content/articles" part but window.location.replace doesnt seem to work.

For example:

 <script type="text/javascript"> window.onload = function() { if (window.location.href.indexOf("/content/articles") > -1) { // Do not redirect } else { // Redirect from www to www1 window.location.replace(window.location.protocol + "//" + window.location.hostname.replace("www", "www1")+window.location.pathname); } } </script> 

You can use window.location.href.replace()

 let url = window.location.href.replace('://www','://www1') console.log(url); 

Here is the example

 <script type="text/javascript"> window.onload = function() { if (window.location.href.indexOf("/content/articles") > -1) { // Do not redirect } else { // Redirect from www to www1 window.location.href = window.location.href.replace('://www','://www1'); } } </script> 

replace('://www','://www1') Also fine since it replace only first occurrence

I can't comment so i am posting it here the answer by @shalitha is correct and there won't be any issue with the replace because with replace only the very first instance is replaced. If you want to replace all the instances then you need to add g ( global) to it, which we don't want here. Details - https://www.w3schools.com/jsref/jsref_replace.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM