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
Post a Comment