[javascript] 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?

This question is related to javascript string

The answer is


short answer: Array.from(string) will give you what you probably want and then you can iterate on it or whatever since it's just an array.

ok let's try it with this string: abc|??\n??|???.

codepoints are:

97
98
99
124
9899, 65039
10
9898, 65039
124
128104, 8205, 128105, 8205, 128103, 8205, 128103

so some characters have one codepoint (byte) and some have two or more, and a newline added for extra testing.

so after testing there are two ways:

  • byte per byte (codepoint per codepoint)
  • character groups (but not the whole family emoji)

_x000D_
_x000D_
string = "abc|??\n??|???"_x000D_
_x000D_
console.log({ 'string': string }) // abc|??\n??|???_x000D_
console.log({ 'string.length': string.length }) // 21_x000D_
_x000D_
for (let i = 0; i < string.length; i += 1) {_x000D_
  console.log({ 'string[i]': string[i] }) // byte per byte_x000D_
  console.log({ 'string.charAt(i)': string.charAt(i) }) // byte per byte_x000D_
}_x000D_
_x000D_
for (let char of string) {_x000D_
  console.log({ 'for char of string': char }) // character groups_x000D_
}_x000D_
_x000D_
for (let char in string) {_x000D_
  console.log({ 'for char in string': char }) // index of byte per byte_x000D_
}_x000D_
_x000D_
string.replace(/./g, (char) => {_x000D_
  console.log({ 'string.replace(/./g, ...)': char }) // byte per byte_x000D_
});_x000D_
_x000D_
string.replace(/[\S\s]/g, (char) => {_x000D_
  console.log({ 'string.replace(/[\S\s]/g, ...)': char }) // byte per byte_x000D_
});_x000D_
_x000D_
[...string].forEach((char) => {_x000D_
  console.log({ "[...string].forEach": char }) // character groups_x000D_
})_x000D_
_x000D_
string.split('').forEach((char) => {_x000D_
  console.log({ "string.split('').forEach": char }) // byte per byte_x000D_
})_x000D_
_x000D_
Array.from(string).forEach((char) => {_x000D_
  console.log({ "Array.from(string).forEach": char }) // character groups_x000D_
})_x000D_
_x000D_
Array.prototype.map.call(string, (char) => {_x000D_
  console.log({ "Array.prototype.map.call(string, ...)": char }) // byte per byte_x000D_
})_x000D_
_x000D_
var regexp = /(?:[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g_x000D_
_x000D_
string.replace(regexp, (char) => {_x000D_
  console.log({ 'str.replace(regexp, ...)': char }) // character groups_x000D_
});
_x000D_
_x000D_
_x000D_


If you want to animate each character you might need to wrap it in span element;

var $demoText = $("#demo-text");
$demoText.html( $demoText.html().replace(/./g, "<span>$&amp;</span>").replace(/\s/g, " "));

I think this is the best way to do it, then process the spans. ( for example with TweenMax)

TweenMax.staggerFromTo( $demoText.find("span"), 0.2, {autoAlpha:0}, {autoAlpha:1}, 0.1 );


New JS allows this:

const str = 'This is my string';
Array.from(str).forEach(alert);

In ES6 / ES2015, you can iterate over an string with iterators,as you can see in

Symbol.iterator MDN

_x000D_
_x000D_
var str = 'Hello';
var it = str[Symbol.iterator]();

for (let v of it) {
  console.log(v)
 }
 
//  "H"
//  "e"
//  "l"
//  "l"
//  "o"
_x000D_
_x000D_
_x000D_

It is a declarative style. What is the advantage? You do not have to concern about how to access each element of the string.


If you want to do a transformation on the text on a character level, and get the transformed text back at the end, you would do something like this:

var value = "alma";
var new_value = value.split("").map(function(x) { return x+"E" }).join("")

So the steps:

  • Split the string into an array (list) of characters
  • Map each character via a functor
  • Join the resulting array of chars together into the resulting string

This should work in older browsers and with UTF-16 characters like .

This should be the most compatible solution. However, it is less performant than a for loop would be.

I generated the regular expression using regexpu

_x000D_
_x000D_
var str = 'My String  ';_x000D_
var regEx = /(?:[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g_x000D_
_x000D_
_x000D_
str.replace(regEx, function (char) {_x000D_
    console.log(char)_x000D_
});
_x000D_
_x000D_
_x000D_

Hope this helps!


How to process each letter of text (with benchmarks)

https://jsperf.com/str-for-in-of-foreach-map-2

for

Classic and by far the one with the most performance. You should go with this one if you are planning to use it in a performance critical algorithm, or that it requires the maximum compatibility with browser versions.

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

for...of

for...of is the new ES6 for iterator. Supported by most modern browsers. It is visually more appealing and is less prone to typing mistakes. If you are going for this one in a production application, you should be probably using a transpiler like Babel.

let result = '';
for (let letter of str) {
  result += letter;
}

forEach

Functional approach. Airbnb approved. The biggest downside of doing it this way is the split(), that creates a new array to store each individual letter of the string.

Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.

// ES6 version.
let result = '';
str.split('').forEach(letter => {
  result += letter;
});

or

var result = '';
str.split('').forEach(function(letter) {
  result += letter;
});

The following are the ones I dislike.

for...in

Unlike for...of, you get the letter index instead of the letter. It performs pretty badly.

var result = '';
for (var letterIndex in str) {
  result += str[letterIndex];
}

map

Function approach, which is good. However, map isn't meant to be used for that. It should be used when needing to change the values inside an array, which is not the case.

// ES6 version.
var result = '';
str.split('').map(letter => {
  result += letter;
});

or

let result = '';
str.split('').map(function(letter) {
  result += letter;
});

One more solution...

var strg= 'This is my string';
for(indx in strg){
  alert(strg[indx]);
}

Most if not all of the answers here are wrong because they will break whenever there is a character in the string outside the Unicode BMP (Basic Multilingual Plane). That means all Emoji will be broken.

JavaScript uses UTF-16 Unicode for all strings. In UTF-16, characters beyond the BMP are made out of two parts, called a "Surrogate Pair" and most of the answers here will process each part of such pairs individually instead of as a single character.

One way in modern JavaScript since at least 2016 is to use the new String iterator. Here's the example (almost) straight out of MDN:

_x000D_
_x000D_
var string = 'A\uD835\uDC68B\uD835\uDC69C\uD835\uDC6A';_x000D_
_x000D_
for (var v of string) {_x000D_
  alert(v);_x000D_
}_x000D_
// "A"_x000D_
// "\uD835\uDC68"_x000D_
// "B"_x000D_
// "\uD835\uDC69"_x000D_
// "C"_x000D_
// "\uD835\uDC6A"
_x000D_
_x000D_
_x000D_


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);
});

You can now use in keyword.

_x000D_
_x000D_
    var s = 'Alien';_x000D_
    for (var c in s) alert(s[c]);
_x000D_
_x000D_
_x000D_


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);
})

You can now iterate over individual Unicode code points contained in a String by using String.prototype[@@iterator], which returns a value of well known Symbol type Symbol.iterator - the default iterator for array-like Objects (String in this case).

Example code:

_x000D_
_x000D_
const str = 'The quick red  jumped over the lazy ! ???!';_x000D_
_x000D_
let iterator = str[Symbol.iterator]();_x000D_
let theChar = iterator.next();_x000D_
_x000D_
while(!theChar.done) {_x000D_
  console.log(theChar.value);_x000D_
  theChar = iterator.next();_x000D_
}_x000D_
_x000D_
// logs every unicode character as expected into the console.
_x000D_
_x000D_
_x000D_

This works with Unicode characters such as emoji or non-roman characters that would trip up legacy constructs.

Reference: MDN Link to String.prototype@@iterator.


you can convert this string into an array of chars using split(), then iterate through it.

_x000D_
_x000D_
const str = "javascript";_x000D_
const strArray = str.split('');_x000D_
_x000D_
strArray.map(s => console.log(s));
_x000D_
_x000D_
_x000D_


It is better to use the for...of statement, if the string contains unicode characters, because of the different byte size.

for(var c of "tree ?") { console.log(c); }
//"A".length === 3

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.


It's probably more than solved. Just want to contribute with another simple solution:

var text = 'uololooo';

// With ES6
[...text].forEach(c => console.log(c))

// With the `of` operator
for (const c of text) {
    console.log(c)
}

// With ES5
for (var x = 0, c=''; c = text.charAt(x); x++) { 
    console.log(c); 
}

// ES5 without the for loop:
text.split('').forEach(function(c) {
    console.log(c);
});

In today's JavaScript you can

Array.prototype.map.call('This is my string', (c) => c+c)

Obviously, c+c represents whatever you want to do with c.

This returns

["TT", "hh", "ii", "ss", " ", "ii", "ss", " ", "mm", "yy", " ", "ss", "tt", "rr", "ii", "nn", "gg"]


Try this code

    function myFunction() {
    var text =(document.getElementById("htext").value); 
    var meow = " <p> <,> </p>";
    var i;


    for (i = 0; i < 9000; i++) {

        text+=text[i] ;



    }

    document.getElementById("demo2").innerHTML = text;

}
</script>
<p>Enter your text: <input type="text" id="htext"/>

    <button onclick="myFunction();">click on me</button>
</p>

You can simply iterate it as in an array:

for(var i in txt){
    console.log(txt[i]);
}

When I need to write short code or a one-liner, I use this "hack":

'Hello World'.replace(/./g, function (char) {
    alert(char);
    return char; // this is optional 
});

This won't count newlines so that can be a good thing or a bad thing. If you which to include newlines, replace: /./ with /[\S\s]/. The other one-liners you may see probably use .split() which has many problems


One possible solution in pure javascript:

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