16

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

2
  • js.do/code/157301 Commented Jun 15, 2017 at 13:22
  • text vs texte Commented Jun 15, 2017 at 13:27

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.