Search code examples
javascriptregexreplacetext-formatting

Regex search two different strings and replace with different values


So I need to process a string in this form:

<Text to be highlighted> word word word word <text again> something ...

So the objective is replacing all the opening < with a <b>and closing > with </b>. However I can not use two different regex one to find < and another to find > because when I run the second one the closing > of the recently created b tag is going to be replaced too.

I'm fully aware that there are many workarounds with javascript and string management, however I would like to use regex for this.

Here is what I've done so far but with the issue I said before.

const expOpening = new RegExp(/</gm);
const expClosing = new RegExp(/>/gm);

input.replace(expOpening, '<b>');
input.replace(expClosing, '</b>');

Solution

  • A global regex replacement should work here:

    var input = "<Text to be highlighted> word word word word <text again> something ...";
    var output = input.replace(/<(.*?)>/g, "<b>$1</b>");
    console.log(input + "\n" + output);