How can I process each letter of text using Javascript?
javascript, string
Solution
If the order of alerts matters, use this:
for (let i = 0; i < str.length; i++) {
alert(str.charAt(i));
}
Or this: (see also this answer)
for (let i = 0; i < str.length; i++) {
alert(str[i]);
}
If the order of alerts doesn't matter, use this:
let i = str.length;
while (i--) {
alert(str.charAt(i));
}
Or this: (see also this answer)
let i = str.length;
while (i--) {
alert(str[i]);
}
var str = 'This is my string';
function matters() {
for (let i = 0; i < str.length; i++) {
alert(str.charAt(i));
}
}
function dontmatter() {
let 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>
Problem
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?
Related problems
- Split JavaScript string into array of codepoints? (taking into account "surrogate pairs" but not "grapheme clusters")
- How can I get a character array from a string?
- What are the most common non-BMP Unicode characters in actual use?
- What is a "surrogate pair" in Java?
- string.charAt(x) or string[x]?
- What are Unicode, UTF-8, and UTF-16?