Reputation: 103
I would like to replace some keywords to HTML elements in a textarea with javascript. Is there any way to replace every 2nd string that has been found?
Just for an example what I mean is: if there are 6 $
signs in the string, the first, third, and fifth would be replaced to HTML tag and the rest to </strong>
HTML tag.
Upvotes: 0
Views: 70
Reputation: 780724
Do the match and replace in pairs with a capture group between them:
string = 'This is a $word$ and $two words$ and a $phrase with several words$.';
newstring = string.replace(/\$([^$]*)\$/g, '<strong>$1</strong>');
console.log(newstring);
Upvotes: 3