views:

41

answers:

1

I have a textarea.I want when I write ,for example "want", to replace it with "two". How to match and replace whole words in javascript?

+2  A: 

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).

References


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)
polygenelubricants
`\blove\b\w` will never match, because `e\b\w` will never match, because there's no `\b` between `e` and `\w`, which are both `\w`.
polygenelubricants
Thank you very much !
lam3r4370