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>

4
  • Did you try window.location.href.replace() ? Commented Dec 19, 2017 at 6:53
  • would be smarter to do this server side. Also no point waiting for window to load either Commented Dec 19, 2017 at 6:58
  • @charlietfl yea.. but my client's requirement is to do it via javascript :( Commented Dec 19, 2017 at 6:58
  • There is another way to refresh @user3188291 Meta Refresh Redirect stackoverflow.com/a/5411567/713789 Commented Dec 19, 2017 at 7:05

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
But it replace(str,str) replaces first occurrence only
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.