Let me suggest a side view, another way to handle what I think you intend to do using Regular expressions with something like:
"test2".replace(/[az]/gi,"M").replace(/[^M]/g,"X") //Outputs "MMMMX"
String.replace will replace a string containing the letters from [az] i at the end of the expression, which means case insensitive. g means searching for all possible matches, not just the first match. In the second expression [^M] this ^ means negation, so everything that is not M will be replaced by X
There is another way to implement a custom function inside String.replace using regular expressions, and it can be implemented as follows:
"test2".replace(/([az])|([^az])/gi, function(m,g1, g2){ return g1 ? "M" : "X"; });
Groups and | are created in regular expression brackets. means either in this expression ([az])|([^az]) there are 2 groups with letters from az, and the other, which means everything that is not az , with the replacement function, which we requested only for the group g1 , if she is a group 1, equal to M otherwise, is X
Another interesting thing you could do is add this function to your entire line, prototyping it like this:
String.prototype.traverse = function(){ return this.replace(/([az])|([^az])/gi,function(m,g1){ return g1 ? "M" : "X" });}
Then it can be used as simply as: "test1".traverse();