How can I process each letter of text using Javascript?

Nic Hubbard picture Nic Hubbard · Dec 27, 2009 · Viewed 515.3k times · Source

I would like to alert each individual letter of a string, but I am unsure how to do this.

So, if I have:

var str = 'This is my string';

I would like to be able to separately alert T, h, i, s, etc. This is just the beginning of an idea that I am working on, but I need to know how to process each letter separately.

I want to use jQuery and was thinking I might need to use the split function after testing what the length of the string is.

Ideas?

Answer

Eli Grey picture Eli Grey · Dec 27, 2009

If the order of alerts matters, use this:

for (var i = 0; i < str.length; i++) {
  alert(str.charAt(i));
}

Or this: (see also this answer)

 for (var i = 0; i < str.length; i++) {
   alert(str[i]);
 }

If the order of alerts doesn't matter, use this:

var i = str.length;
while (i--) {
  alert(str.charAt(i));
}

Or this: (see also this answer)

 var i = str.length;
while (i--) {
  alert(str[i]);
}

var str = 'This is my string';

function matters() {
  for (var i = 0; i < str.length; i++) {
    alert(str.charAt(i));
  }
}

function dontmatter() {
  var i = str.length;
  while (i--) {
    alert(str.charAt(i));
  }
}
<p>If the order of alerts matters, use <a href="#" onclick="matters()">this</a>.</p>

<p>If the order of alerts doesn't matter, use <a href="#" onclick="dontmatter()">this</a>.</p>