检查数组项的字符串(多个单词)

问题描述 投票:-1回答:4

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

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

javascript regex
4个回答
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'))

0
投票

使用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');
}

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
投票

试试这个:

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']))
© www.soinside.com 2019 - 2024. All rights reserved.