最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to replace the second occurrence of a string in javascript - Stack Overflow

programmeradmin113浏览0评论

I am trying to replace the second occurrence of a string in javascript. I'm using a regex to detect all the matches of the character that I'm looking for. The alert returns the same initial text.

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

I am trying to replace the second occurrence of a string in javascript. I'm using a regex to detect all the matches of the character that I'm looking for. The alert returns the same initial text.

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

Share Improve this question edited Jul 8, 2019 at 8:53 KubiRoazhon asked Jun 15, 2017 at 13:20 KubiRoazhonKubiRoazhon 1,8393 gold badges25 silver badges53 bronze badges 2
  • js.do/code/157301 – Patrick Roberts Commented Jun 15, 2017 at 13:22
  • text vs texte – Nina Scholz Commented Jun 15, 2017 at 13:27
Add a ment  | 

1 Answer 1

Reset to default 36

It's because you never use the result returned by the replace function.

Here's the corrected code:

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

console.log(result)

发布评论

评论列表(0)

  1. 暂无评论