0

I would like to replace a digit in a number (the third, for example), but that replaces the first. Why ?

var x = "1111";
var x = x.replace(x[2],"2");
// output : 2111,
// but I would have liked : 1121
  • The problem is because `x[2]` returns `1`, and `replace()` only works on the first instance it finds - the first `1` in the string in this case. You need to explicitly chop up the string using `subtr()` and concatenating the changes. See the duplicate for more information – Rory McCrossan Jul 09 '20 at 15:10
  • Understood !.... Thanks. – user9626146 Jul 09 '20 at 15:43

0 Answers0