-2

How do I replace the first character of a string with another character? I am casting the number as string.

Example: String 12341 New string: 92341

I tried this script but cant figure a way to only replace the first character.

var oldStr =12341;
var newStr = oldStr.replace(1, 9);
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
Shaji
  • 741
  • 2
  • 9
  • 23

1 Answers1

0
  1. oldStr is not a string, it's a number.

  2. replace has to replace characters, not numbers.

  3. So coerce the number to a string, and then do the replacement.

const oldStr = 12341;
const newStr = oldStr.toString().replace('1', '9');
console.log(newStr);
Andy
  • 61,948
  • 13
  • 68
  • 95