5

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>
user3188291
  • 567
  • 1
  • 9
  • 22

2 Answers2

6

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

Shalitha Suranga
  • 1,138
  • 8
  • 24
  • 1
    Hi. thanks for your reply. Just in case the URL contains www at the path name, im afraid it would replace it as well. Example: www.abc.com.sg/testwww.html would be redirected www1.abc.com.sg/testwww1.html. Is it possible to just limiting it to the hostname? – user3188291 Dec 19 '17 at 06:56
  • 2
    But it `replace(str,str)` replaces first occurrence only – Shalitha Suranga Dec 19 '17 at 07:08
0

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

Ashish Kumar
  • 168
  • 12