您的位置:首页 > Web前端 > JavaScript

[JS Array]Find an item in an array that contains a string and then return that string

2018-03-21 12:40 681 查看
[A JavaScript question from stackoverflow.com]
question:

I have an array of strings.
I want to search in that array for and string that contains a specific string.
If it's found, return that string WITHOUT the bit of the string we looked for.
So, the array has three words. "Strawbery", "Lime", "Word:Word Word"
I want to search in that array and find the full string that has "Word:" in it and return "Word Word"
[译]
有一个字符串数组,查找含有指定字符串的项,返回该项中不包含指定字符串的字符串
例如一个数组中包含 “Strawbery”“Lime”“Word:Word Word”,搜索包含字符串“Word:”的项,然后返回“Word Word”
answer:
You can use
find
to search the array. And use
replace
to remove the string.
This code will return the value of you want only.
[译]使用find()方法遍历数组,然后使用replace()方法移除不需要的字符串,即可得到你想要的字符串。let arr = ["Strawbery", "Lime", "Word:Word Word"];
let search = "Word:";

let result = (arr.find(e => e.includes(search)) || "").replace(search, '');

console.log(result);if there are multiple search results, you can use
filter
and
map

[译]假如有重复的搜索结果,使用filter()和map()
let arr = ["Strawbery", "Word:Lime", "Word:Word Word"];
let search = "Word:";

let result = arr.filter(e => e.includes(search)).map(e => e.replace(search, ''));

console.log( result );
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: