【问题标题】:How to replace the second occurrence of a string in javascript [duplicate]如何替换javascript中第二次出现的字符串[重复]
【发布时间】:2021-09-01 13:04:38
【问题描述】:

我正在尝试替换 javascript 中第二次出现的字符串。我正在使用正则表达式来检测我正在寻找的字符的所有匹配项。警报返回相同的初始文本。

text = 'BLABLA';
//var count = (texte.match(/B/g) || []).length;
var t=0;   
texte.replace(/B/g, function (match) {
t++;
return (t === 2) ? "Z" : match;
});
alert(text);

https://js.do/code/157264

【问题讨论】:

标签: javascript


【解决方案1】:

这是因为您从不使用replace 函数返回的结果。

这是更正后的代码:

const text = 'BLABLA'
let t = 0
const result = text.replace(/B/g, match => ++t === 2 ? 'Z' : match)

console.log(result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-20
    • 2020-07-10
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 2012-02-07
    相关资源
    最近更新 更多