我有一个字符串(超过1个单词)和一个数组,我想检查字符串,并查找该字符串是否包含数组中的任何字符串。
我试过使用include方法但是如果我的匹配字符串只有一个单词就可以了。例如
var arr = ['2345', '1245', '0987'];
var str = "1245"
console.log(str.includes('1245'));
这会有效,但我希望将它与句子相匹配。
var arr = ['2345', '1245', '0987'];
var str= "Check if the number 1245 is present in the sentence."
我想检查字符串中是否存在此数字。
你可以使用find
var arr = ['2345', '1245', '0987'];
var str= "Check if the number 1245 is present in the sentence."
let found = (str) => arr.find(e => {
return str.includes(e)
}) || `${str} Not found in searched string`
console.log(found(str))
console.log(found('878787'))
使用Array.prototype.some
结合String.prototype.indexOf
:
var a = ['2345', '1245', '0987'];
var s = "Check if the number 1245 is present in the sentence.";
var t = "No match here";
function checkIfAnyArrayMemberIsInString(arr, str) {
return arr.some(x => str.indexOf(x) !== -1);
}
if (checkIfAnyArrayMemberIsInString(a, s)) {
console.log('found');
} else {
console.log('not found');
}
if (checkIfAnyArrayMemberIsInString(a, t)) {
console.log('found');
} else {
console.log('not found');
}
你可以在阵列上使用some()
。
var arr = ['2345', '1245', '0987'];
var str= "Check if the number 1245 is present in the sentence."
console.log(arr.some(x => str.includes(x)));
如果您只想检查由空格分隔的单词,请使用split,然后使用includes()
var arr = ['2345', '1245', '0987'];
var str= "Check if the number 1245 is present in the sentence."
let parts = str.split(' ')
console.log(arr.some(x => parts.includes(x)));
试试这个:
function matchWord(S, A) {
let matchesWord = false
S.split(' ').forEach(word => {
if (A.includes(word)) matchesWord = true;
});
return matchesWord;
}
console.log(matchWord('Check for the number 1245', ['2345', '1245', '0987']))