2
I’m doing an exercise that asks me to turn the word Roberto in Roberta using the method replace()
, and by my logic this solution should work:
var roberto = 'Roberto';
roberto.replace( roberto.charAt(6), 'a' );
// Raberto
Using the charAt()
and passing the letter position by parameter works smoothly with all other letters of the word, but when I step to position 6, that would be just the letter I need (the last in the case) it takes the second letter instead of the last. Would anyone know to tell me why this occurs?
OBS.: The solution HAS than using the method replace()
.
Just one observation: charAt(6) is an object, so you would have to convert it to string.
– Ivan Ferrer
It would be something like this:
var roberto = 'Roberto', op = (roberto.charAt(6)).toString();
roberto.replace(op, 'a');
and yet you would still be:Raberto
, because simple replace is only executed in the first character found.– Ivan Ferrer
It would be the same as
roberto.replace('o', 'a');
to work, you would have to do so:var roberto = 'Roberto', op = new RegExp((roberto.charAt(6)).toString()+"$", 'gim'); roberto.replace(op, 'a');
– Ivan Ferrer