Search code examples
javascriptregexreplaceregular-languageregexp-replace

How to modify this javascript highlight regex to not re-highlight itself?


I have this code:

display_title = 'Example text landscapes / more text';
// highlight landscapes
display_title = display_title.replace(/landscapes/gi,'<b>landscapes</b>');
// but also need to highlight some instances of "/"
display_title = display_title.replace(/\//gi,'<b>/</b>');
// ... more words to highlight

How should I modify the code so that the second highlight command would NOT replace the slash inside the landscapes</b> ? In other words, it should only match outside of html tags.

I found some examples but these were using jQuery, I want to do it with normal JavaScript.


Solution

  • Either match landscapes or a forward slash, then replace with the matched text surrounded by <b>:

    const display_title = 'landscapes /';
    const result = display_title.replace(/landscapes|\//gi, '<b>$&</b>');
    console.log(result);