I made this AngularJS 1.x filter, to search using a the same SQL LIKE
syntax. Right now only the percentage symbol (%
) is supported, the underscore symbol (_
) is not.
Under the hood I'm simply building a RegExp from a format string passed as a parameter (ie. the search string), then I'm looping over all the object properties inside an input array (first parameter).
I'm looking for some feedback about performance, and in particular about any possible "edge cases" in which it would perform bad or could possibly break.
Here's the code (ES6/ES2015 syntax):
"use strict";
export default function likeFilter() {
return (input, format) => {
if (!(input instanceof Array && "string" === typeof format && format.length)) {
return input;
}
const like = format.indexOf("%") >= 0;
const startLike = like && format.charAt(0) === "%";
const endLike = like && format.charAt(format.length - 1) === "%";
const split = [];
split.splice(0, 0, ...format.split("%"));
if (startLike) {
split.shift();
}
if (endLike) {
split.pop();
}
let regexp = split.join(".*");
if (!startLike) {
regexp = "^" + regexp;
}
if (!endLike) {
regexp += "$";
}
regexp = new RegExp(regexp, "mi");
return input.filter(el => {
for (let key in el) {
if (el.hasOwnProperty(key)) {
if (regexp.test(el[key])) {
return true;
}
}
}
return false;
});
}
};
Example usage:
JS code (angular filters module):
"use strict";
import likeFilter from "./like";
filtersModule.filter("like", likeFilter);
HTML code (angular template):
<input type="text" ng-model="data.searchstring" />
<div ng-repeat="obj in data.objs | like : data.searchstring"><!-- [...] --></div>