是否可以使用javascript重定向URL的主机名?
如果URL包含“content / articles”,则它应保留在同一URL中。否则,它应该将所有其他URL从www重定向到www1。
我想我得到了“/ content / articles”部分,但window.location.replace似乎没有用。
例如:
<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>
你可以使用window.location.href.replace()
let url = window.location.href.replace('://www','://www1')
console.log(url);
这是一个例子
<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')
也很好,因为它只替换第一次出现
我无法发表评论所以我在这里发布@shalitha的答案是正确的,并且替换不会有任何问题,因为替换只有第一个实例被替换。如果要替换所有实例,则需要向其添加g(全局),这是我们不想要的。详情 - https://www.w3schools.com/jsref/jsref_replace.asp