1

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 "?

2
  • There are plenty of JS syntax highlighters freely available. Are you sure you want to reinvent the wheel? Commented Feb 18, 2011 at 17:35
  • Yes, this is for my personal API. Commented Feb 18, 2011 at 19:31

1 Answer 1

3

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>');
Sign up to request clarification or add additional context in comments.

1 Comment

Bah.. why didn't I think of this!? Works as expected, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.