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

时间:2014-10-14 12:42:55

标签: javascript jquery

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

这就是我尝试的内容,但无论您在哪个网站上,它似乎都会将您重定向到新位置。

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

有什么想法吗?

3 个答案:

答案 0 :(得分:3)

在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>

答案 1 :(得分:1)

我认为:

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

或者同样不太可读:

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

答案 2 :(得分:0)

怎么样:

   var fullUrlLink = location.href;

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