在javascript中匹配并替换整个单词 [英] Match and replace whole words in javascript

查看:115
本文介绍了在javascript中匹配并替换整个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个textarea,当我写,例如,想要,我想用两个替换它。

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

如何在javascript中匹配和替换整个单词?

How can I match and replace whole words in javascript?

推荐答案

您可以使用单词boundary \b ,所以 \ bwant \ b 。请记住,单词的正则表达式定义可能不适合您。 Javascript正则表达式将单词边界定义为单词字符 \w 之间的位置,即 [a-zA-Z0-9 _] 和一个非单词字符(除此之外的所有内容)。

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

  • regular-expressions.info/Word boundaries

  • 中有一个 \ bcan \b 不能(因为'不是 \ w

  • 没有 \\ \\ blove \b in love_me(因为 e _ 都是 \ w

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

这篇关于在javascript中匹配并替换整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆