Javascript正则表达式,不会匹配html标签旁边的单词

发布于 2024-12-17 11:48:03 字数 543 浏览 1 评论 0原文

我在 contenteditable div 上使用 jquery 拼写检查器插件,它在返回时插入 div 和 brs。拼写检查器的正则表达式不会匹配标签旁边拼写错误的单词。这是我正在执行正则表达式的 div 的内容:

Praesent commodo cursus magna,
<br>
<br>
dsf
<br>
vel scelerisque nisl consectetur et.

这是循环中的 javascript,并且“replaceWord”是拼写错误的单词:

var re = new RegExp('(^|[^a-zA-Z])(' + replaceWord + ')([^a-zA-Z]|$)', 'g');
html = html.replace(re, '$1<span class="spellcheck-word-highlight">$2</span>$3');

不过,正则表达式正确匹配所有其他单词。 有什么想法吗?

谢谢!

I'm using the jquery spellchecker plugin on a contenteditable div, which inserts divs and brs on return. The spellchecker's regex won't match an incorrectly spelled word which is next to a tag. Here is the contents of div i'm performing the regex on:

Praesent commodo cursus magna,
<br>
<br>
dsf
<br>
vel scelerisque nisl consectetur et.

Here is the javascript, which is in a loop, and 'replaceWord' is an incorrectly spelled word:

var re = new RegExp('(^|[^a-zA-Z])(' + replaceWord + ')([^a-zA-Z]|$)', 'g');
html = html.replace(re, '$1<span class="spellcheck-word-highlight">$2</span>$3');

The regex correctly matches all other words though.
Any thoughts?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无名指的心愿 2024-12-24 11:48:03

我会尝试:

var re = new RegExp('\\b(' + replaceWord + ')\\b', 'g');

相反。 “\b”限定符(在上面的字符串中双反斜杠)匹配从非单词字符(或文本开头)到单词字符的转换,以及单词字符到非单词字符(或文本结尾)的转换。

I'd try:

var re = new RegExp('\\b(' + replaceWord + ')\\b', 'g');

instead. The "\b" qualifier (backslash doubled in the strings above) matches the transition from non-word character (or beginning of text) to word character, and word character to non-word character (or end of text).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文