Allow me to offer a side view, another way handle what I think you intent to do by using Regular Expressions with something like:
"test2".replace(/[a-z]/gi,"M").replace(/[^M]/g,"X") //Outputs "MMMMX"
String.replace
will replace an string that contains letters from [a-z]
the i
at the end of the expression means case insensitive. g means will search for all possible matches and not just the first match. In the second expression [^M]
this ^
means negation so anything that is not an M
will be replaced with X
.
There is another way in which we implement a custom function within the String.replace
using Regular Expressions and it can be implemented like this:
"test2".replace(/([a-z])|([^a-z])/gi,
function(m,g1, g2){
return g1 ? "M" : "X";
});
In regular expression parenthesis creates groups and | means or in this expression ([a-z])|([^a-z])
there 2 groups one with letters from a-z and the other which means everything that is not a-z
with the replace function we asked only for group g1
if it is group 1 is M
otherwise is an X
.
Another cool thing you could do is add this function to all your string by prototyping it like:
String.prototype.traverse = function(){ return this.replace(/([a-z])|([^a-z])/gi,function(m,g1){ return g1 ? "M" : "X" });}
Then it can be used as simple as: "test1".traverse();