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:
- Take the string and convert it into an array
- Loop over the array
- Replace each instance of the aforementioned numbers with the appropriate replacements using .replace()
- 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.
.replace"returns a new string"...String.replacedoesn't work in place. You have to assign the result somewhere ...String.prototype.replaceAll, likestring.replaceAll('5', 'S').replaceAll('0', 'O')array[i] = array[i].replace('5', 'S');. But I recomment using the solution from my previous comment.return string.replace(/5/g, 'S').replace(/0/g, 'O').replace(/1/g, 'I')