I have this regex on mongodb query to match words by prefix:
{sentence: new RegExp('^'+key,'gi')}
What would be the right regex pattern if I want it to match a sentence that has at least a word starting with key
prefix? For example:
If I have a sentence
"This is a dog"
when key
is 'do', then it should match that sentence since prefix 'do' is a substring of 'dog'.
My solution as of now only works for the first word of the sentence. It so far only matches that sentence if I type in 't' or 'th' or 'this'. It wouldnt match that sentence whenever I type in 'i' (prefix for 'is') or 'do' (prefix for 'dog').
You can use the expression /\bprefix\w+/
. This should match any word starting with "prefix"
. Here the \b
represents a word boundary and \w
is any word character.
If you don't want to get the whole word, you can just do /\bprefix/
. If you want to put this in a string, you also have to escape the \
: '\\bprefix'
.
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