string正则expression式replace节点js

我在我的节点js中有下面的string

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."; 

这里我想用<b class =\"b_1\">*</b>replace<b class =\"b_1\">*</b> 。 输出是Your 1 payment due is $4000.Your 2 payment due is $3500. Your 3 payment due is $5000. Your 1 payment due is $4000.Your 2 payment due is $3500. Your 3 payment due is $5000.

如果这是一个正常的replace,我不会有任何问题,但在这里我认为最好的替代方法是使用正则expression式。 这是我困惑的地方。 在java中我们有一个stringVariableName.replaceAll()方法。 请让我知道我该怎么做。

谢谢

       

网上收集的解决方案 "string正则expression式replace节点js"

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

说明

 <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 

那么我们用代表<b></b>标签内容的第一个捕获组$1replace整个匹配。


例:

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

你不一定需要一个正则expression式,但使用jQuery,你可以很容易地删除孩子,并使用经典的单行版返回HTML:

 textReplaced = $('<div>').html(textToReplace).children().remove().end().html(); 

在这里工作的小提琴 – https://jsfiddle.net/7cgb51ju/

我会用这样的东西:

 textToReplace.replace(/<b class =\"b_1\">[0-9]+<\/b>/g, ''); 

你只需要使用正则expression式捕获组与下面的正则expression式 /<b.*?>(.*?)<\/b>/g ,然后你可以在你的代码中使用它:

 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."; console.log(textToReplace.replace(/<b.*?>(.*?)<\/b>/g, '$1'));