我的节点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.";
我希望将<b class =\"b_1\">*</b>
替换为''
。输出为Your 1 payment due is $4000.Your 2 payment due is $3500. Your 3 payment due is $5000.
。
如果这是正常的替换我不会有任何问题,但在这里我认为最好的替换方法是使用Regex。这是我感到困惑的地方。在java中,我们有一个stringVariableName.replaceAll()
方法。请让我知道我该怎么做。
由于
答案 0 :(得分:3)
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
然后我们将整个匹配项替换为第一个捕获的组$1
,该组代表<b></b>
标记的内容。
示例:强>
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);
答案 1 :(得分:0)
您不一定需要RegEx,但使用jQuery可以轻松删除子项并使用经典的单行返回HTML:
textReplaced = $('<div>').html(textToReplace).children().remove().end().html();
这里的工作小提琴 - https://jsfiddle.net/7cgb51ju/
答案 2 :(得分:0)
我会用这样的东西:
textToReplace.replace(/<b class =\"b_1\">[0-9]+<\/b>/g, '');
答案 3 :(得分:0)
您只需要将 Regex capturing groups 与以下 Regex /<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'));
此处'$1'
将保留(.*?)
的第一个捕获组。