Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

traverse a string char by char javascript

function SimpleSymbols(str) { 
    var letter =['a','b','c','d','e','f','g','h','i','j',
    'k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];

    var newstr = "";
    for (var i = 0; i<str.length; i++){
        if (str.charAt(i).toLowerCase() in letter){
            newstr += "M";
        }
        else{
            newstr += "X";
        }
    }

return newstr; 

}

If str is "Argument goes here" it returns XXXXXXXXX. WHy doesn't it return MMMMMMMMMM?

like image 849
Michael Sacks Avatar asked Aug 25 '14 16:08

Michael Sacks


1 Answers

you do not look up an entry in an array with in. use indexOf() to find the position of an array entry. indexOf() will return the position or -1 if no entry is found.

for (var i = 0; i<str.length; i++){
    var strChar = str.charAt(i).toLowerCase();

    if ( letter.indexOf(strChar) >= 0 ) {
        newstr += "M";
    }
…
like image 111
dreamlab Avatar answered Oct 20 '22 17:10

dreamlab