Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I process each letter of text using Javascript?

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?

like image 310
Nic Hubbard Avatar asked Dec 27 '09 17:12

Nic Hubbard


People also ask

How do you split letters in JavaScript?

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.

How can we iterate through individual words in a string in JavaScript?

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).

Which method is used to extract every character from the text in JavaScript?

There are 3 methods for extracting string characters: charAt(position) charCodeAt(position) Property access [ ]

Can you use forEach on a string?

You can't use it on a string because it's not available on the String prototype.


1 Answers

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>
like image 189
Eli Grey Avatar answered Oct 13 '22 17:10

Eli Grey