如何检查字符串是否包含 JavaScript 中子字符串数组中的文本? [英] How to check if a string contains text from an array of substrings in JavaScript?
问题描述
非常直接.在 javascript 中,我需要检查一个字符串是否包含数组中的任何子字符串.
Pretty straight forward. In javascript, I need to check if a string contains any substrings held in an array.
推荐答案
没有任何内置功能可以为您做到这一点,您必须为它编写一个函数,尽管它可以只是对 <代码>一些数组方法.
There's nothing built-in that will do that for you, you'll have to write a function for it, although it can be just a callback to the some
array method.
适合您的两种方法:
- 数组
some
方法 - 正则表达式
数组 some
方法(在 ES5 中添加)使这变得非常简单:
The array some
method (added in ES5) makes this quite straightforward:
if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
// There's at least one
}
使用箭头函数和新的 includes
方法(ES2015+)甚至更好:
Even better with an arrow function and the newish includes
method (both ES2015+):
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 you know the strings don't contain any of the characters that are special in regular expressions, then you can cheat a bit, like this:
if (new RegExp(substrings.join("|")).test(string)) {
// At least one match
}
...它创建一个正则表达式,它是您要查找的子字符串的一系列替代(例如,one|two
)并测试以查看是否它们中的任何一个都有匹配项,但是如果任何子字符串包含正则表达式中的任何特殊字符(*
、[
等),则您必须首先逃避他们,你最好只做无聊的循环.有关转义它们的信息,请参阅此问题的答案.
...which creates a regular expression that's a series of alternations for the substrings you're looking for (e.g., one|two
) and tests to see if there are matches for any of them, but if any of the substrings contains any characters that are special in regexes (*
, [
, etc.), you'd have to escape them first and you're better off just doing the boring loop instead. For info about escaping them, see this question's answers.
现场示例:
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}"`);
}
这篇关于如何检查字符串是否包含 JavaScript 中子字符串数组中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!