I'm a novice at regex, so hopefully some expert can just yawn at my question with an easy answer. I'm trying to find and replace words that start with a certain letter and keep them plural if they are plural.
So, for example, I want to replace replace the word "boy" with "band", and "boys" with "bands"
text.replace( /\b(b)[\w]+(s?)\b/gi, "<span style=\"font-weight:bold\">$1and$2<\/span>" );
However, $2 isn't coming up with the optional "s".
Thanks ahead of time!
Simply change [\w]+
to [\w]+?
.
This changes
from "greedy" (match as many characters as possible and only give characters up if forced to)
which means s?
will not match because [\w]+
already did it for us. (wrong behavior)
to "lazy" (match as few characters as possible, only adding to the match if absolutely necessary)
which gives s?
an opportunity to match. (correct behavior)
By the way: You can change [\w]+?
to \w+?
and it will work exactly the same.
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