I have created a list in react that on key up the list can be filtered. My handler currently looks like this – but it only works on whole word matches and blanks on a result when the user starts typing or starts to add spaces to type the remaining words.
initialCommands: [
{
"label": "Order more plasters",
"icon": ShoppingCart
},
{
"label": "Book a meeting with my doctor",
"icon": Bell
}
]
typeHandler(data){
const regex = new RegExp(`\b(${data.command})\b`, "gi");
const result = initialCommands.filter(function(item) {
return item.label.match(regex);
});
this.setState({
prunedCommands: result,
prunedCommandsReady: true
});
}
2
Answers
I believe the regex needs to be updated. Try adding something like the following, note the period and asterisk.
Whenever I’m messing with regex, I use this website. https://regex101.com/
A very simple pure js filtering solution without using regular expressions.
startsWith
to match string with the start positionincludes
to match strings without caring about position