2
\$\begingroup\$

I would like to turn the following:

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

into

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

\$\endgroup\$
  • \$\begingroup\$ Maybe you are optimizing too early here. \$\endgroup\$ – Joseph Feb 17 '13 at 0:31
  • \$\begingroup\$ 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. \$\endgroup\$ – Joseph Silber Feb 17 '13 at 1:15
3
\$\begingroup\$

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>')
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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