JSFiddle - React, Tailwind, and code Playground
by dswitzer
JavaScript
function filterList(q, list) {
function escapeRegExp(s) {
return s.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
}
var words = q
.split(/\s+/g)
.map(function (s){ return s.trim(); })
.filter(function (s){ return !!s; });
var hasTrailingSpace = q.endsWith(" ");
var searchRegex = new RegExp(
words
.map(function (word, i){
if (i + 1 === words.length && !hasTrailingSpace) {
// The last word - ok with the word being "startswith"-like
return "(?=.*\\b" + escapeRegExp(word) + ")";
} else {
// Not the last word - expect the whole word exactly
return "(?=.*\\b" + escapeRegExp(word) + "\\b)";
}
})
.join("") + ".+",
"gi"
);
console.log("words -> %o", words);
console.log("searchRegex -> %o", searchRegex);
console.log("list -> %o", list);
var x = list.filter(function (item){
// since we have a global search, we need to reset the search mar
searchRegex.lastIndex = 0;
return searchRegex.test(item);
});
console.log("x -> %o", x);
return x;
}
console.log(filterList("hello", ["world", "hello there", "my hello friend"]));