I would like to alert each 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 was thinking I might need to use the split function after testing what the length of the string is.
How can I do this?
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
Simple for loop can use for in iterate through words in a string JavaScript. And for iterate words in string use split, map, and join methods (functions).
There are 3 methods for extracting string characters: charAt(position) charCodeAt(position) Property access [ ]
You can't use it on a string because it's not available on the String prototype.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With