JavaScript: 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.

[..."aπŸ˜ƒc"].forEach( ((x) => { console.log(x); }) );

// prints
// a
// πŸ˜ƒ
// c

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

If string contains emoji or rare Unicode character, for-loop behaves in unexpected way. (for why, see [see JS: String Code Unit] )

const str = "aπŸ˜ƒc";

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

// prints
// a
// οΏ½
// οΏ½
// c

JavaScript String

BUY
Ξ£JS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Property

Object and Inheritance

Array

Function

Constructor/Class

Iterable 🌟

Misc