I'm pretty sure the fastest way is to loop over the larger string and for each character check if the shorter string contains it:
function containsAny(haystack, needles){
for(var i = 0; i < haystack.length; i++){
for(var j = 0; j < needles.length; j++){
if(haystack[i] === needles[j]) {
return true;
}
}
}
return false;
}
Here's some evidence:
http://jsperf.com/stringcontainsany
EDIT:
Actually, string.indexOf
is faster than indexing into the string, so this is more efficient:
function containsAny(haystack, needles) {
for (var i = 0; i < haystack.length; i++) {
if (needles.indexOf(haystack[i]) !== -1) {
return true;
}
}
return false;
}