0

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.

1
  • Could you please show example of input string and expected output? Commented Nov 14, 2018 at 23:41

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

6 Comments

Damn. I was SO overcomplicating that, trying to work with lookaheads and lookbehinds and all. Massive props. I want to like this one TWICE!
Yeah, it's easy to get a mental block if you don't think about things in the right way. You were so focused on the $, you didn't think about the phrases.
That gets replaced with the string that was captured by the capture group. Any regexp tutorial will explain this.
@Roelly, take a look at the MDN article on regex, and search the page for "capturing groups". developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Also see this tutorial
|

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.