views:

167

answers:

6

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 hot to process each letter separately.

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

Ideas?

+11  A: 

One possible solution in pure javascript:

for (var x = 0; x < str.length; x++)
{
    var c = str.charAt(x);
    alert(c);
}
The MYYN
It would probably be better with var x = 0 and var c = str.charAt(x).
Rich
Also, str.length should be stored in a variable so it doesn't have to keep being accessed.
Eli Grey
A: 

You can access single characters with str.charAt(index) or str[index]. But the latter way is not part of ECMAScript so you better go with the former one.

Gumbo
I'd stay away from that. Unfortunately that doesn't work in all versions of IE. Trust me. I learned it the hard way.
Xavi
It is part of ECMAScript, but only in newly-released 5th edition, not 3rd.
kangax
+1  A: 

You can try this

var arrValues = 'This is my string'.split('');
// Loop over each value in the array.
$.each(
    arrValues,
    function( intIndex, objValue ){
     alert(objValue);
    };
    )
astander
+1  A: 

Concise solution below. Note that it's safer to write curly braces on the same line in JavaScript.

var s = "hello world";

for(i in s) { 
  alert(s.charAt(i));
}
Chandra Patni
Why is it safer?
Pool
See semicolon insertion section in this article: http://oreilly.com/javascript/excerpts/javascript-good-parts/awful-parts.html
Chandra Patni
You're iterating over properties, not string character indices. This won't work if you extend String.prototype with an enumerable property.
Eli Grey
A: 

You can get an array of the individual characters like so

var test = "test string",
    characters = test.split('');

and then loop using regular Javascript, or else you can iterate over the string's characters using jQuery by

var test = "test string";

$(test.split('')).each(function (index,character) {
    alert(character);
});
Rich
+1  A: 

I'm surprised nobody has put down this simple solution that doesn't keep re-using str.length yet.

If the order of alerts matter to you, use this:

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

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

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