简体   繁体   中英

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

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM