I am writing a search bar with an autocomplete feature that is hooked up to an endpoint. I am using regex to determine the "context" that I am in inside of the query I type in the search bar. The three contexts are "attribute," "value," and "operator." The two operators that are allowed are "AND" and "OR." Below is an example of an example query.
Color: Blue AND Size: "Women's Large" (<-- multi-word values or attribute names are surrounded by quotation marks)
I need my regex to match after you put a space after Blue, and if the user begins type "A/AN/AND/O/OR", I need it to match. Once they have put a space after the operator, I need it to stop matching.
This is the expression I have come up with.
const contextIsOperator = /[\w\d\s"]+: *[\w\s\d"]+ [\w]*$/
It matches once I put a space after "Blue," but matches for everything I put after that. If I replace the last * in the expression with a +, it works when I put a space after "Blue" and start manually typing one of the operators, but not if I just have a space after "Blue."
The pattern I have in my head written in words is:
How do I solve this problem?
Change [\w]* to something that just matches AND, OR, or one of their prefixes. Then you can make it optional with ?
[\w\s"]+: *[\w\s"]+ (A|AN|AND|O|OR)?$
DEMO
Note that Size: Women's Large won't match this because the apostrophe isn't in \w; that only matches letters, digits, and underscore. You'll need to add any other punctuation characters that you want to allow in these fields to the character set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With