Проверить строку (более одного слова) для элемента массива - PullRequest
0 голосов
/ 18 апреля 2019

У меня есть строка (более 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 голосов
/ 18 апреля 2019

Попробуйте это:

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']))
0 голосов
/ 18 апреля 2019

Вы можете использовать найти

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 голосов
/ 18 апреля 2019

Использование 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 голосов
/ 18 апреля 2019

Вы можете использовать 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)));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...