如何检查数组中的字符串是否在URL/window.location.pathname中

How to check if one of the strings from an array are in the URL/window.location.pathname

本文关键字:是否 URL pathname location window 字符串 何检查 检查 数组      更新时间:2023-09-26

我有一个数组:

var checkURL = ['abc123', 'abc124', 'abc125'];

如何检查数组中的字符串是否存在于window.location.pathname中?

我知道我可以单独使用:

<script type="text/javascript">
    $(document).ready(function () {
        if(window.location.href.indexOf("abc123") > -1) {
           alert("your url contains the string abc123");
        }
    });
</script> 

使用for循环进行线性搜索。

$(document).ready(function () {
    var checkURL = ['abc123', 'abc124', 'abc125'];
    for (var i = 0; i < checkURL.length; i++) {
        if(window.location.href.indexOf(checkURL[i]) > -1) {
            alert("your url contains the string "+checkURL[i]);
        }
    }
});

这是一个使用join和正则表达式的选项。

var checkURL = ['abc123', 'abc124', 'abc125'];
var url = window.location.href;
var Matches = RegExp(checkURL.join('|')).exec(url);
if (Matches) {
    alert('your url contains the string ' + Matches[0]);
}

jsFiddle例子。

使用for循环:

$(document).ready(function () {
    for (var i = 0; i < checkURL.length; i++) {
        if(window.location.href.indexOf(checkURL[i]) > -1) {
           alert("your url contains the string " + checkURL[i]);
        }
    }
});

您可以将测试数据转换为映射

var checkURL = {'abc123':'', 'abc124':'', 'abc125':''};
var url = window.location.pathname.split('/');
for(var i=0;i<url.length;i++){
var targetUrl=url[i];
if(typeof checkURL[targetUrl]!=='undefined'){
alert(targetUrl);
}
}

作为参考,这个优雅的解决方案:

var checkURL = ['abc123', 'abc124', 'abc125'];
var inArray = checkURL.some(function(el) {
    return ~location.href.indexOf(el);
}); // true/false

注意:这需要some方法的垫片!

循环可以这样做:

for(var p in checkURL){
   if(window.location.pathname.indexOf(checkURL[p]) > -1){
      alert("your url contains the string");
   }
}

在你的问题中标记了jquery,使用each()函数

jQuery.each(checkURL, function(i,v) {
if(window.location.href.indexOf(checkURL[i]) > -1) {
           alert("your url contains the string " + checkURL[i]);
        }
});

不需要使用i和v变量作为描述键值对