Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • https://www.abc.com.sg/content/articles will remain the same URL.
  • https://www.abc.com.sg redirect to https://www1.abc.com.sg

<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>
like image 313
user3188291 Avatar asked Dec 19 '17 06:12

user3188291


People also ask

Can you redirect using JavaScript?

You can redirect a web page to another page in a number of ways including server-side redirects, HTML meta refresh redirects and JavaScript redirects.

What syntax do you use to redirect a URL with JavaScript?

href Property. The simplest and most common way to use JavaScript to redirect to a URL is to set the location property to a new URL using window. location. href.


1 Answers

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

like image 88
Shalitha Suranga Avatar answered Oct 02 '22 22:10

Shalitha Suranga