What's wrong with replace method?


#1

I tried to make a script which takes my text and randomly make characters upper case. But I see that the first characters are mostly upper case and the last ones more and more lower case and I don't know why it is.
And if I write an exact letter several times it capitalize just the first side of it like "AAAAAAAAAAAAAaaaaaaaa".


var text = prompt("Write your text here:");



 
for (var i = 0; i < text.length; i++) {
randomnum = i * Math.round(Math.random());

text = text.replace(text[randomnum], text[randomnum].toUpperCase());

};
alert(text);


#2

replace will replace the first instance of the matching query (in the case of all the a's, the first a it can find. so you instead you might want to something like:

text[randomnum] = text[randomnum].toUpperCase();

(untested), but should work, or you can think of a way, i hope you understand what is wrong with the replace function


#3

It is interesting because it doesn't stop at the first 'a' or 'd' or anything else. For example if I write 'abcd' 4 times, it alerts:
ABCDABcDAbcDabcdabcd


#4

but still, you can see the first instance of the random chosen letter is converted to uppercase. after the c goes to lowercase, you will never see a uppercase C after the lowercase, since then replace would replace the first lowercase c it can find

Replace will replace the first instance of the lowerletter it can find


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.