javascript - Wrapping multiple words with HTML tags using RegExp -


i'm using regexp make quick replacements in potentially large set of text. it's doing providing means syntax highlighting:

var text = 'throw new error("foo");'; text = text.replace(/(^|\w)(throw|new|error)(\w|$)/g,'$1<span class="syntax-reserved-word">$2</span>$3'); 

problem is, highlights "throw" , "error" skips right on "new". regexp specifies beginning of string or non-word, throw or new or error, non-word or end of string. after finds "^throw ", wouldn't search position begin @ n in "new", meaning should match "^new "?

try \b (word boundary) instead of non-word-char:

text = text.replace(/\b(throw|new|error)\b/g,'<span class="syntax-reserved-word">$1</span>'); 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -