JavaScript: Iterate String

By Xah Lee. Date: . Last updated: .

Ways to loop thru a string:

Using For-Loop

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

Using For-Of Loop

for (let x of "aπŸ˜ƒc") { console.log(x); }

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

[see for-of Loop]

Convert to Array to Loop

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

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

JavaScript String

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc