如何判断数组是否包含任何子字符串

时间:2020-06-11 04:28:33

标签: javascript arrays ecmascript-6

我有一个包含javascript字符串的数组,看起来像这样:

let array = ['cat', 'dog', 'bird']

,我的字符串中有一些用|隔开的单词 这是字符串:

let string = 'pig|cat|monkey' 

那么我怎么知道我的数组中的字符串中是否至少包括这些项之一?

4 个答案:

答案 0 :(得分:1)

您可以使用Array方法.some()

检查字符串中是否存在数组中的动物
const animals = ['cat', 'dog', 'bird']
const string = 'pig|cat|monkey'
const splitString = string.split('|')


const hasAnimals = animals.some(animal => splitString.includes(animal))

您可以使用Array方法.reduce()

获得存在的动物
const presentAnimals = splitString.reduce((acc, animal) => {
  const animalExists = animals.includes(animal)
  if (animalExists) {
    acc.push(animal)
  }
  return acc
}, [])

或者,如果您需要一支班轮

const presentAnimals = splitString.reduce((acc, animal) => animals.includes(animal) ? [...acc, animal] : [...acc], [])

答案 1 :(得分:1)

split字符串乘|trim每个单词。 使用数组includes来检查some字。

const has = (arr, str) =>
  str.split("|").some((word) => arr.includes(word.trim()));

let array = ["cat", "dog", "bird"];
let string = "pig|cat|monkey";

console.log(has(array, string));
console.log(has(array, "rabbit|pig"));

答案 2 :(得分:0)

使用字符|分割字符串,然后运行forEach循环并检查数组中是否存在parts的值。

let array = ['cat', 'dog', 'bird', 'monkey'];
let str = 'pig|cat|monkey';
//split the string at the | character
let parts = str.split("|");
//empty variable to hold matching values
let targets = {};
//run a foreach loop and get the value in each iteration of the parts
parts.forEach(function(value, index) {
  //check to see if the array includes the value in each iteration through
  if(array.includes(value)) {
    targets[index] = value; //<-- save the matching values in a new array    
    //Do something with value...
  }
})
console.log(targets);
I have an array with javascript strings that looks something like this: let array = ['cat', 'dog', 'bird'] and I have some words inside my string that are separated by a | this is the string: let string = 'pig|cat|monkey' so how do I know if my array
includes at least one of these items within my string?

答案 3 :(得分:0)

请尝试以下操作:-

let array = ['cat', 'dog', 'bird'];

let string = 'ca';

var el = array.find(a =>a.includes(string));

console.log(el);