user3188291
user3188291

Reputation: 577

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>

Upvotes: 5

Views: 7954

Answers (2)

Shalitha Suranga
Shalitha Suranga

Reputation: 1146

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

Upvotes: 6

Ashish Kumar
Ashish Kumar

Reputation: 188

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

Upvotes: 0

Related Questions