简体   繁体   中英

Javascript regex, wont match words next to html tag

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!

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

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