我遇到了一个问题,我在JS中有一个类似的字符串数组:
var myArray = ["bedroomone", "bedroomonetwo", "bathroom"];
我想检索数组中包含关键字' bedroom'的所有元素。我怎样才能取得这样的成绩?
我尝试了不同的方式而没有获得理想的结果。我该怎么办?
答案 0 :(得分:5)
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(仅限现代浏览器):
var PATTERN = 'bedroom',
filtered = myArray.filter(function (str) { return str.includes(PATTERN); });
答案 1 :(得分:2)
Using `Javascript arrow function` is much simpler
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
// search using keyword from array
var keywordToSearch = 'Arslan'; // word to search
var keyword = keywordToSearch.toLowerCase();
var names = [{id: 1, name: 'Aqib'}, {id: 2, name: 'Arslan'}];
//search keyword from names array by name
var searchResult = names.filter(word => word.name.toLowerCase().indexOf(keyword) > -1);
console.log(searchResult);
// expected output: > Array [Object { id: 2, name: "Arslan" }]
Using javascript arrow function
答案 2 :(得分:1)
var bedrooms = myArray.filter(name => name.includes('bedroom'))
答案 3 :(得分:0)
改进了Microfed对此的答案
var textToSearch = 'bedroom';
var filteredArray = myArray.filter((str)=>{
return str.toLowerCase().indexOf(textToSearch.toLowerCase()) >= 0;
});
答案 4 :(得分:0)
您还可以使用search()方法
在正则表达式搜索中查找第一个子字符串匹配项。
(方法)String.search(regexp:字符串| RegExp):数字(+1重载)
const filterList = (data, query) => {
return data.filter(name => name.toLowerCase().search(query.toLowerCase()) !== -1);
};