Match and replace whole words in javascript

I have a textarea, and when I write, for example, "want", I want to replace it with "two".

How can I match and replace whole words in javascript?



You can use the word boundary \b, so \bwant\b. Do keep in mind that the regex definition of a word may not suit you, though. Javascript regex defines word boundaries as the place between a word character \w, which is [a-zA-Z0-9_] and a non-word character (everything except that).


Examples of word boundary caveats

  • There's a \bcan\b in "can't" (because ' is not a \w)
  • There's no \blove\b in "love_me"(because e and _ are both \w)


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.