Javascript 根据内容过滤数组中的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35235794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter strings in Array based on content
提问by prince
I am running into an issue, I have a similar array of Strings in JS:
我遇到了一个问题,我在 JS 中有一个类似的字符串数组:
var myArray = ["bedroomone", "bedroomonetwo", "bathroom"];
And I would like to retrieve all the elements in the array that contains the keyword 'bedroom'. How can I achieve such result ?
我想检索包含关键字“卧室”的数组中的所有元素。我怎样才能达到这样的结果?
I tried in different ways without getting the desired result. How should I proceed ?
我尝试了不同的方法,但没有得到想要的结果。我应该如何进行?
回答by Microfed
var PATTERN = 'bedroom',
filtered = myArray.filter(function (str) { return str.indexOf(PATTERN) === -1; });
var PATTERN = /bedroom/,
filtered = myArray.filter(function (str) { return PATTERN.test(str); });
String.prototype.includes(only in moderm browsers):
String.prototype.includes(仅在现代浏览器中):
var PATTERN = 'bedroom',
filtered = myArray.filter(function (str) { return str.includes(PATTERN); });
回答by Ania Zielinska
var bedrooms = myArray.filter(name => name.includes('bedroom'))
回答by Moh .S
Improved Microfed's answer to this
改进了 Microfed 对此的回答
var textToSearch = 'bedroom';
var filteredArray = myArray.filter((str)=>{
return str.toLowerCase().indexOf(textToSearch.toLowerCase()) >= 0;
});
回答by Ardenne
You could also use the search() method
您还可以使用 search() 方法
Finds the first substring match in a regular expression search.
(method) String.search(regexp: string | RegExp): number (+1 overload)
在正则表达式搜索中查找第一个子字符串匹配。
(方法) String.search(regexp: string | RegExp): number (+1 重载)
const filterList = (data, query) => {
return data.filter(name => name.toLowerCase().search(query.toLowerCase()) !== -1);
};