Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to turn the following:

<div>this is a $test</div>


<div>this is a <div>$test</div></div>

currently I have

var regexp = new RegExp('$([^\\s]*)','g'),
    html = '<div>this is a $test</div>',
    matched = html.match(regexp)[0]

if (matched){
   html = html.replace(match, '<div>' + match + '</div>')

which works, but is there a more concise way of doing this?

share|improve this question
Maybe you are optimizing too early here. – Joseph the Dreamer Feb 17 '13 at 0:31
match only returns an array if it found anything, otherwise it just returns null. So be careful there, html.match(regexp)[0] will give you a typeError if no match was found. – Joseph Silber Feb 17 '13 at 1:15
up vote 3 down vote accepted

Sure, use String.replace. As an added bonus, it doesn't fail when there is no match:

'<div>this is a $test</div>'.replace(/(\$\w+)/g, '<div>$1</div>')
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.