I have new RegExp(`\\b${escapedQuery}`, "i")
regex to search words boundary , where escapedQuery
is escaped value after lodash's escapeRegExp function.
const BRANDS = [
"Alexander McQueen",
"Alexandre De Paris",
"alexander.t",
"A.W.A.K.E. MODE",
"alexanderwang.t",
"MARC JACOBS (THE)"
];
function filter(query) {
return BRANDS.filter((brand) => {
const escapedQuery = escapeRegExp(query);
const re = new RegExp(`\\b${escapedQuery}`, "i");
return re.test(brand);
});
}
But if I pass a dot or bracket symbol, then I don't get the value I expected.
console.log(filter("al")); // OK [ "Alexander McQueen", "Alexandre De Paris", "alexander.t", "alexanderwang.t"]
console.log(filter("M")); // OK [ "Alexander McQueen", "A.W.A.K.E. MODE", "MARC JACOBS (THE)"]
console.log(filter(".")); // Expected [""] - Actual ["alexander.t", "A.W.A.K.E. MODE", "alexanderwang.t"]
console.log(filter("(")); // OK [""]
console.log(filter(")")); // Expected [""] - Actual ["MARC JACOBS (THE)"]
Here is Sandbox to better understanding expected and actual results
What needs to be fixed in the expression so that it returns the expected value?
CodePudding user response:
You can require the first char to be always a word char:
function filter(query) {
return BRANDS.filter((brand) => {
const re = new RegExp(`(?=\\w)${query.replace(/[-\/\\^$* ?.()|[\]{}]/g, '\\$&')}`, "i");
return re.test(brand);
});
}
See the demo below:
const BRANDS = [
"Alexander McQueen",
"Alexandre De Paris",
"alexander.t",
"A.W.A.K.E. MODE",
"alexanderwang.t",
"MARC JACOBS (THE)"
];
function filter(query) {
return BRANDS.filter((brand) => {
const re = new RegExp(`(?=\\w)${query.replace(/[-\/\\^$* ?.()|[\]{}]/g, '\\$&')}`, "i");
return re.test(brand);
});
}
console.log(filter("al")); // OK [ "Alexander McQueen", "Alexandre De Paris", "alexander.t", "alexanderwang.t"]
console.log(filter("M")); // OK [ "Alexander McQueen", "A.W.A.K.E. MODE", "MARC JACOBS (THE)"]
console.log(filter(".")); // Expected [""] - Actual ["alexander.t", "A.W.A.K.E. MODE", "alexanderwang.t"]
console.log(filter("(")); // OK [""]
console.log(filter(")")); // Expected [""] - Actual ["MARC JACOBS (THE)"]