I am trying to create a simple function that replaces all instances of a certain character in a string in JS. In this instance, I want to replace all a
's with o
's.
I am pretty sure the code is right, but the output is still the original string.
function replaceLetter(string){
for(var i = 0; i < string.length; i++){
if(string[i] == 'a'){
console.log(string[i]);
string[i] = 'o'
}
}
return string;
}
replaceLetter('hahaha') // returns 'hahaha'
Why isn't it replacing a's with o's?
I always like using
split()
andjoin()
Strings in Javascript are immutable, and thus any changes to them aren't going to be reflected as you might expect.
Consider just using the
string.replace()
function instead:You can use a regular expression like this:
Or use another string to accumulate the result like this:
Assuming you want to use a
for
loop:You have to build a new string like this, because as mentioned in a comment, strings are immutable. You can write
string[4] = 'b'
and it won't cause an error, but it won't do anything either.It's probably overkill, but you could use
reduce
, which does the looping internally and maintains theresult
variable:However, for this particular case, the regexp solution shown in other answers is probably preferable.