I am looking to find a keyword match in a string. I am trying to use word boundary, but this may not be the best case for that solution. The keyword could be any word, and could be preceded with a non-word character. The string could be any string at all and could include all three of these words in the array, but I should only match on the keyword:
['hello', '#hello', '@hello'];
Here is my code, which includes an attempt found in post:
let userStr = 'why hello there, or should I say #hello there?';
let keyword = '#hello';
let re = new RegExp(`/(#\b${userStr})\b/`);
re.exec(keyword);
- This would be great if the string always started with #, but it does not.
- I then tried this
/(#?\b${userStr})\b/
, but if the string does start with#
, it tries to match##hello
. - The
matchThis
str could be any of the 3 examples in the array, and the userStr may contain several variations of thematchThis
but only one will be exact
You need to account for 3 things here:
\b
word boundary is a context-dependent construct, and if your input is not always alphanumeric-only, you need unambiguous word boundariesUse
Pattern description
(?:^|\\W)
- a non-capturing string matching the start of string or any non-word char(${keyword.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')})
- Group 1: a keyword value with escaped special chars(?!\\w)
- a negative lookahead that fails the match if there is a word char immediately to the right of the current location.Check whether the keyword already begins with a special character. If it does, don't include it in the regular expression.