string regex replace in node js

22,516
var newString = textToReplace.replace(/<b.*?>(.*?)<\/b>/g, '$1');

Explanation:

<b.*?> : matches the <b ...> opening tag (using the non-greedy quantifier to match as few as possible)
(.*?)  : matches the content of the <b></b> tag (should be grouped so it will be used as a replacement text), it uses the non-greedy quantifier too.
<\/b>  : matches the closing tag
g      : global modifier to match as many as possible

then we replace the whole match with the first captured group $1 which represents the content of the <b></b> tag.


Example:

var str = "Your <b class =\"b_1\">1</b> payment due is $4000.Your <b class =\"b_1\">2</b> payment due is $3500. Your <b class =\"b_1\">3</b> payment due is $5000.";

var newString = str.replace(/<b.*?>(.*?)<\/b>/g, "$1");

console.log(newString);

Regex101 example.

Share:
22,516
user3872094
Author by

user3872094

Updated on July 09, 2022

Comments

  • user3872094
    user3872094 almost 2 years

    I'm having the below string in my node js.

    var textToReplace = "Your <b class =\"b_1\">1</b> payment due is $4000.Your 
    <b class =\"b_1\">2</b> payment due is $3500. Your <b class =\"b_1\">3</b> 
    payment due is $5000.";
    

    Here I want to replace <b class =\"b_1\">*</b> with ''. The output is Your 1 payment due is $4000.Your 2 payment due is $3500. Your 3 payment due is $5000..

    If this is a normal replace I wouldn't have had any problem, but here I think the best way to replace is by using Regex. This is where I'm confused. In java we have a stringVariableName.replaceAll() method. please let me know how can I do this.

    Thanks

    • ibrahim mahrir
      ibrahim mahrir almost 7 years
      var newString = textToReplace.replace(/<b.*?\/b>\s*/g, '');. Regex101 example. Read about the global modifier and the non-greedy regexps.
    • user3872094
      user3872094 almost 7 years
      @ibrahimmahrir, Thanks for the quick reply. my bad, I actually forgot the actual replaced string, can you please look into my updated question.
    • ibrahim mahrir
      ibrahim mahrir almost 7 years
      var newString = textToReplace.replace(/<b.*?>(.*?)<\/b>/g, '$1');. Regex101 example.
  • ibrahim mahrir
    ibrahim mahrir almost 7 years
    ehem ehem. He said nodeJS.