如果当前url包含,JS将用户重定向到不同的页面

JS redirect user to different page if the current url contains .

本文关键字:重定向 用户 url 包含 JS 如果      更新时间:2023-09-26

我使用的软件不允许我直接编辑某些页面。如果观众正在查看的页面包含某个字符串,我想将他们重定向到另一个URL。

这是我尝试过的,但它似乎会将你重定向到新的位置,无论你在网站的哪个页面上。

<script>
var EDITURL = window.location.href;
if ('url:contains("testthis")') {
window.location.replace("http://www.test.com");
};
</script>

有什么想法吗?

在JavaScript中,'url:contains("testthis")'被视为一个字符串,并且是truthy。

if('your text'){
  // code here will always be executed.
}

这个代码应该工作:

<script>
    if(document.location.href.indexOf('testthis') > -1) { 
        // indexOf will return the position of the first occurence of this string in the url
        // or -1 it it's not there.
        document.location.href = 'http://www.test.com';
    }
</script>

如我所见:

if(EDITURL.indexOf('testthis') > -1) { ... }

或者同样可读性较差:

if(~EDITURL.indexOf('testthis')) { ... }

关于:

   var fullUrlLink = location.href;
   if (fullUrlLink.search("/yourelement/") >= 0) {
       window.location.replace("http://stackoverflow.com");
   } else {
       window.location.replace("http://stackoverflow.com");
   }