查找字符串中存在哪个数组元素

时间:2019-07-11 13:07:51

标签: javascript arrays string ecmascript-6

是否有任何方法或快速方法来查看数组中的哪些元素存在于字符串中?

const myArray = ['foo', 'bar', 'baz'];
const myString = 'somelongbarstring';

在此示例中,bar中存在数组中的myString,因此我需要根据barmyArray获得myString

1 个答案:

答案 0 :(得分:11)

findincludes一起使用:

const myArray = ['foo', 'bar', 'baz'];
const myString = 'somelongbarstring';

const res = myArray.find(e => myString.includes(e));

console.log(res);

如果要查找字符串中包含的所有项目,请将find换为filter

const myArray = ['foo', 'bar', 'baz'];
const myString = 'somelongbarstring-baz';

const res = myArray.filter(e => myString.includes(e));

console.log(res);

如果需要索引,请使用findIndex

const myArray = ['foo', 'bar', 'baz'];
const myString = 'somelongbarstring';

const res = myArray.findIndex(e => myString.includes(e));

console.log(res);

多个索引有点棘手-您必须使用Array.prototype.keys方法来保留原始索引,因为filter返回具有新索引的新数组:

const myArray = ['foo', 'bar', 'baz'];
const myString = 'somelongbarstring-baz';

const res = [...myArray.keys()].filter((e, i, a) => myString.includes(myArray[e]));

console.log(res);

(您也可以在上述函数中将e换成i,但是这样做比较容易理解,因为我们要遍历键。) < / p>