JS: Iterate String
Loop thru characters in string
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
you can convert string to array, using Array.from.
console.log( Array.from("a🦋c"), ); // [ "a", "🦋", "c" ]
Array.from also lets you apply a function to the array.
// using Array.from to map a function over characters in string console.log( Array.from( "a🦋c", (x, i) => `char at index ${i} is ${x}`, ), ); /* [ "char at index 0 is a", "char at index 1 is 🦋", "char at index 2 is c" ] */
when you have an array, you can use array methods.
- JS: Array.prototype.map
- JS: Array.prototype.forEach
- JS: Array.prototype.flatMap
- JS: Array.prototype.filter
Spread Operator
Spread Operator can be used to convert string to array of characters, or as function arguments.
// spread operator on string 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 */