Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Replace the first character

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var oldStr =12341;
var newStr = oldStr.replace(1, 9);

>Solution :

  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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading