很简单。在JavaScript中,我需要检查一个字符串是否包含数组中包含的任何子字符串。
很简单。在JavaScript中,我需要检查一个字符串是否包含数组中包含的任何子字符串。
没有内置的方法可以为您完成此操作,您必须编写一个函数,尽管它可以只是some
数组方法的回调函数。
你有两种方法:
some
方法some
数组some
方法(在ES5中添加)使这变得非常简单:
if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
// There's at least one
}
使用箭头函数和新的includes
方法(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 (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}"`);
}
.some
,你如何返回匹配的那个? - Serginosome
,而是使用 find
,它返回第一个使您的回调函数返回 truthy 值的元素,如果回调从未返回 truthy 值,则返回 undefined
。 - T.J. Crowdersome
可能会处理那个问题... - Serginolet x; if (array.some((v) => { if (/*... v matches condition ... */) { x = v; return true; } return false; })) { /*... use
x here ... */ }
这样的事情时,才需要这么做。但在这种情况下,使用 find
更简单、更符合习惯。我展示的唯一真正的原因是当 undefined
实际上在数组中 并且 它是你想要找到的内容时。(使用 find
你不会知道是否已经找到它,或者没有找到任何东西。而使用上述方法,你可以区分出来)。非常罕见的情况... - T.J. CrowdersubstringsArray.some(substring=>yourBigString.includes(substring))
var yourstring = 'tasty food'; // the string to check against
var substrings = ['foo','bar'],
length = substrings.length;
while(length--) {
if (yourstring.indexOf(substrings[length])!=-1) {
// one of the substrings is in yourstring
}
}
function containsAny(str, substrings) {
for (var i = 0; i != substrings.length; i++) {
var substring = substrings[i];
if (str.indexOf(substring) != - 1) {
return substring;
}
}
return null;
}
var result = containsAny("defg", ["ab", "cd", "ef"]);
console.log("String was found in substring " + result);
对于正在谷歌搜索的人,
正确的答案应该是。
const substrings = ['connect', 'ready'];
const str = 'disconnect';
if (substrings.some(v => str === v)) {
// Will only return when the `str` is included in the `substrings`
}
以下是我认为迄今为止最佳解决方案的内容(仅代表个人意见)。它是一种现代化的(ES6)方案,具有以下特点:
some()
函数不同,该方法不仅返回布尔值(true/false)享受吧!
const arrayOfStrings = ['abc', 'def', 'xyz'];
const str = 'abc';
const found = arrayOfStrings.find(v => (str === v));
在这种情况下,found
将被设置为“abc”。这将适用于精确字符串匹配。
如果您改用:
const found = arrayOfStrings.find(v => str.includes(v));
在这种情况下,found
将再次被设置为 'abc'。这不允许部分匹配,因此如果 str 被设置为 'ab',found
将未定义。
const found = arrayOfStrings.find(v => v.includes(str));
相反,如果str设置为'ab',则found
将设置为'abc'。
非常简单!
var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = 0, len = arr.length; i < len; ++i) {
if (str.indexOf(arr[i]) != -1) {
// str contains arr[i]
}
}
var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = arr.length - 1; i >= 0; --i) {
if (str.indexOf(arr[i]) != -1) {
// str contains arr[i]
}
}
len
变量,只需检查 i < arr.length
即可。 - GreySageconst str = 'Does this string have one or more strings from the array below?';
const arr = ['one', 'two', 'three'];
const contains = arr.some(element => {
if (str.includes(element)) {
return true;
}
return false;
});
console.log(contains); // true
arr.some(element => str.includes(element) ? true : false)
。 - jasonleonhardsubstringsArray.every(substring=>yourBigString.indexOf(substring) === -1)
完全支持;)
对于完整的支持(除了@ricca的版本)。
wordsArray = ['hello', 'to', 'nice', 'day']
yourString = 'Hello. Today is a nice day'.toLowerCase()
result = wordsArray.every(w => yourString.includes(w))
console.log('result:', result)
map()
函数吗?我记得曾经读过相关的内容... - Martin Hennings