按内容过滤数组? [英] Filter array by content?
问题描述
我正在尝试过滤不基于对象的数组,并且我需要过滤器来简单地检查数组的每个部分以查找特定的字符串.
I'm trying to filter an array that is non-object based, and I need the filter to simply check each piece of the array for a specific string.
说我有这个数组:
["http://mywebsite.com/search", "http://mywebsite.com/search", "http://yourwebsite.com/search"]
我需要做的是以某种方式收集数组,以便获得一个仅包含以http://mywebsite.com
开头而不是http://yourwebsite.com
What I need to do is harvest the array in a way so that I get a new array that only contain those who start with http://mywebsite.com
and not http://yourwebsite.com
最后得出的结论是:["http://mywebsite.com/search", "http://mywebsite.com/search", "http://yourwebsite.com/search"]
进入此["http://mywebsite.com/search", "http://mywebsite.com/search"]
推荐答案
您可以使用String的.filter()
和.startsWith()
方法过滤数组.
You can filter the array using .filter()
and .startsWith()
method of String.
从文档开始:
startsWith()
方法确定字符串是否以指定字符串的字符开头,并根据需要返回true或false.
The
startsWith()
method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.
演示:
let data = ["http://mywebsite.com/search",
"http://mywebsite.com/search",
"http://yourwebsite.com/search"];
let result = data.filter(s => s.startsWith('http://mywebsite.com/'));
console.log(result);
如您的评论中所述;如果您想检查多个字符串,则可以尝试以下操作:
As mentioned in your comment; if you wants to check multiple strings then you can try this:
let data = ["http://mywebsite.com/search",
"http://mywebsite.com/find",
"http://yourwebsite.com/search",
"http://yourwebsite.com/find"];
let strToMatch = ["http://mywebsite.com/search", "http://mywebsite.com/find"];
let result = data.filter(s1 => strToMatch.some(s2 => s2.startsWith(s1)));
console.log(result);
文档:
这篇关于按内容过滤数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!