检查一个数组项的字符串(一个以上的单词)

时间:2019-04-18 17:50:09

标签: javascript regex

我有一个字符串(超过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."

我想检查字符串中是否存在这个数字。

4 个答案:

答案 0 :(得分:0)

您可以在阵列上使用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)));

答案 1 :(得分:0)

您可以使用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'))

答案 2 :(得分:0)

结合使用Array.prototype.someString.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');
}

答案 3 :(得分:-1)

尝试一下:

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']))