If I want to do a "whole word" search for a string with special characters, like say "A+", how can I write a Javascript regex that will match the whole word for cases like the following:
- Is the only text in the string: "A+"
-
Is at the end of the string: "You got an A+"
-
Is at the beginning of the string: "A+ good job!"
-
Is in the middle: "You did A+ work here."
It should return false for:
-
Not whole word: "A++"
-
Not whole word": "You got an A++!"
-
Other special characters that make it not a whole word: "A+,", "A+-", "A+0", "A+=", "A+"", "A+*", "A+/", etc.
… and many other cases
I’d love to just use b:
/b(A+)b/g
…but that seems to interact poorly with special characters (in fact I’m not sure that regex can even match anything…).
2
Answers
You can use lookarounds for this:
Here we search for
A+
surrounded by whitespace symbols or line boundaries.Outputs:
Demo here
EDIT: How correctly noticed @trincot you can use negative lookarounds with non-whitespace meta sequence to avoid alterations:
If you have an environment where a lookbehind assertion is not supported, you can use a capture group.
Explanation
(?:^|s)
Assert the start of the string or match a whitespace character(A+)
MatchA
and+
(?!S)
Assert a whitespace boundary to the rightRegex demo