Justin
Justin

Reputation: 13

Wrapping multiple words with HTML tags using RegExp

I'm using RegExp to make some quick replacements in a potentially large set of text. What it's doing is providing a means for 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, it highlights "throw" and "Error" but skips right over "new". My RegExp specifies beginning of string or non-word, then throw or new or Error, non-word or end of string. So after it finds "^throw ", wouldn't the search position begin at the n in "new", meaning it should match "^new "?

Upvotes: 1

Views: 402

Answers (1)

Floern
Floern

Reputation: 33904

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

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

Upvotes: 3

Related Questions