我有两个字符串我想检查下面另一个变量的一个变量的子字符串是否是代码片段。
var val1 = "www.google.com , www.yahoo.com , www.msn.com, in.news.yahoo.com";
var val2 = "in.news.yahoo.com/huffington-post-removes-sonia-gandhi-rich-list-103404344.html";
//if val1 does not contains val2 I want to show popup. I tried val1 .toLowerCase().indexOf(val2 .toLowerCase()) but it doesn't work it always return -1.
任何人都可以建议我如何处理条件?
答案 0 :(得分:1)
试试这个:
var val1 = "www.google.com,www.yahoo.com,www.msn.com,in.news.yahoo.com";
var val2 = "www.yahoo.com/huffington-post-removes-sonia-gandhi-rich-list-103404344.html";
function check(){
var val1_arr = val1.split(',');
for(var i = 0; i < val1_arr.length; i++){
if(val2.indexOf(val1_arr[i]) != -1){
// val2 contains val1
return true;
}
}
return false;
}
答案 1 :(得分:0)
试试这个:
val1 = [ "www.google.com",
"www.yahoo.com",
"www.msn.com",
"in.news.yahoo.com" ];
function showPopUpIfUrlIsInVal1(val2) {
var b = false;
for (var i = 0; i < val1.length; i++)
{
if (val2.indexOf(val1[i]) > -1)
{
b = true;
break;
}
}
if (b)
{
alert("test message");
}
}
showPopUpIfUrlIsInVal1("http://www.google.com");
答案 2 :(得分:0)
啊,这是一个有趣的,这是解决这个问题的FP方式:
var val1 = "www.google.com , www.yahoo.com , www.msn.com,in.news.yahoo.com";
var val2 = "in.news.yahoo.com/huffington-post-removes-sonia-gandhi-rich-list-103404344.html";
function arrayInString(needles, haystack, callback) {
var result = needles.some(function(el) {
return haystack.indexOf(el.trim()); // Trim is required to remove extra whitespace
});
if (result) callback();
}
arrayInString(val1.split(","), val2, function() {
// Create your popup here
});
答案 3 :(得分:0)
您可以使用Array.prototype.filter方法:
//fixing val1 format
var val1 = "www.google.com , www.yahoo.com , www.msn.com , in.news.yahoo.com";
var matched = val1.split(' , ').filter(function (v) {
return ~val2.indexOf(v);
});