gpt4 book ai didi

javascript - Node js中的字符串正则表达式替换

转载 作者:搜寻专家 更新时间:2023-11-01 00:29:15 24 4
gpt4 key购买 nike

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

这里我想替换<b class =\"b_1\">*</b>'' .输出为 Your 1 payment due is $4000.Your 2 payment due is $3500. Your 3 payment due is $5000. .

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

谢谢

最佳答案

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


Regex101 example .

关于javascript - Node js中的字符串正则表达式替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43983591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com