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

How to use Javascript .replace() method within a for loop?

I am attempting to take a given string and replace a given number in that string with a character. Specifically:

  • 5 is to be replaced with "S"
  • 1 is to be replaced with "I"
  • 0 is to be replaced with "O"

(this is a Kata exercise)

I have written a function which should:

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

  1. Take the string and convert it into an array
  2. Loop over the array
  3. Replace each instance of the aforementioned numbers with the appropriate replacements using .replace()
  4. Return the joined string.

My code is as appears below

Function correct(string) {
let array = string.split('')
  for (let i = 0; i < array.length; i++) {
    array[i].replace('5', 'S')
    array[i].replace('0', 'O')
    array[i].replace('1', 'I')
  }
  return array.join('');
}

The function returns the string exactly as initially provided, unchanged. I suspect my issue is with the way I’ve used the .replace() method within the loop, or the index positions declared.

>Solution :

String.prototype.replace returns a new string and does not mutate the variable it was executed on.
That’s why you need to assign the result of replacement somewhere.

To fix your code just do the following with each replacement:

array[i] = array[i].replace('5', 'S');

Note 1: since array[i] is always a single character, there is no need in replace, because you can just compare like so:

if (array[i] === '5') {
  array[i] = 'S';
}

or oneliner:

array[i] = array[i] === '5' ? 'S' : array[i];

Note 2: for loop for a replacement is not a clean code. JavaScript is very flexible and provides much better solutions to the problem. Eg. String.prototype.replaceAll.

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