Reputation: 577
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
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
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