JS: Iterate String

By Xah Lee. Date: . Last updated: .

Enumerate Chars in String via For-Of Loop

Best way to go thru each char in string is using for-of Loop.

for (let x of "a🦋c") console.log(x);
/*
a
🦋
c
*/

Convert String to Array

Another way is to convert string to array, then use any array methods to go thru.

console.log(Array.from("a🦋c"))
 // [ "a", "🦋", "c" ]

console.log([..."a🦋c"])
// [ "a", "🦋", "c" ]

Using For-Loop (go thru 16-bit units)

Using for-loop is not recommended, because it goes thru code unit, not characters.

const xx = "a🦋c";
for (let i = 0; i < xx.length; i++) {
 console.log(xx[i]);
}
/*
a
�
�
c
*/

JavaScript. String