traverse a string char by char javascript

Michael Sacks picture Michael Sacks · Aug 25, 2014 · Viewed 13.3k times · Source
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?

Answer

dreamlab picture dreamlab · Aug 25, 2014

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";
    }
…