如何检查字符串是否包含来自JavaScript中子字符串数组的文本?
2022-08-30 00:20:18
非常简单。在javascript中,我需要检查字符串是否包含数组中包含的任何子字符串。
非常简单。在javascript中,我需要检查字符串是否包含数组中包含的任何子字符串。
没有任何内置的东西可以帮你做到这一点,你必须为它编写一个函数,尽管它可以只是对数组方法的回调。some
为您提供两种方法:
some
some
数组方法(在ES5中添加)使这变得非常简单:some
if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
// There's at least one
}
使用箭头函数和新方法(均为ES2015 +)甚至更好:includes
if (substrings.some(v => str.includes(v))) {
// There's at least one
}
实际示例:
const substrings = ["one", "two", "three"];
let str;
// Setup
console.log(`Substrings: ${substrings}`);
// Try it where we expect a match
str = "this has one";
if (substrings.some(v => str.includes(v))) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
// Try it where we DON'T expect a match
str = "this doesn't have any";
if (substrings.some(v => str.includes(v))) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
如果您知道字符串不包含正则表达式中任何特殊字符,那么您可以作弊一下,如下所示:
if (new RegExp(substrings.join("|")).test(string)) {
// At least one match
}
...它创建了一个正则表达式,该正则表达式是您要查找的子字符串(例如,)的一系列交替,并进行测试以查看其中任何一个是否有匹配项,但是如果任何子字符串包含正则表达式(,等)中特殊的任何字符,则必须首先对它们进行转义,并且最好只是执行无聊的循环。有关转义它们的信息,请参阅此问题的答案。one|two
*
[
实际示例:
const substrings = ["one", "two", "three"];
let str;
// Setup
console.log(`Substrings: ${substrings}`);
// Try it where we expect a match
str = "this has one";
if (new RegExp(substrings.join("|")).test(str)) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
// Try it where we DON'T expect a match
str = "this doesn't have any";
if (new RegExp(substrings.join("|")).test(str)) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
一条生产线解决方案
substringsArray.some(substring=>yourBigString.includes(substring))
如果子字符串返回true\false
exists\does'nt exist
需要 ES6 支持