JavaScript Reference ยท String
String.prototype[Symbol.iterator]()
Reference for the JavaScript string iterator: how for...of, spread and Array.from walk a string by code point, and where graphemes still split.
A string is iterable. Its Symbol.iterator method returns an iterator that yields the string one code point at a time, each as a short string. This is what makes for...of, spread ([...text]), Array.from(text) and destructuring work on strings.
Unlike indexing with text[i], which gives you UTF-16 code units, the iterator keeps surrogate pairs together, so an emoji comes out as one item instead of two broken halves.
const iterator = string[Symbol.iterator]();
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
string[Symbol.iterator]() for (const codePoint of string) { /* ... */ } [...string]
| Part | Description |
|---|---|
| Parameters | None. |
| Return value | A string iterator object with a next() method. Each result's value is a string of one code point (one or two code units). |
| Exceptions | None. |
Usage notes
- Where it is used implicitly:
for...of, array spread,Array.from(),new Set(string), destructuring (const [first, second] = "hello") andyield*. - Pairs stay together. A valid surrogate pair is yielded as one two-unit string. A lone surrogate (a broken half) is yielded by itself.
- Not grapheme-aware. Combining marks, skin-tone modifiers, flags and ZWJ sequences span several code points, and each is yielded separately. Use
Intl.Segmenterto walk what readers see as one symbol. - The iterator is itself iterable and single-use: once
doneistrue, create a new one withstring[Symbol.iterator](). - Counting code points:
[...text].lengthworks, but allocates an array. For very long strings, loop withfor...ofand count. - Reverse carefully.
text.split("").reverse().join("")breaks emoji becausesplit("")splits by code units. Spread first. - Differences from indexing:
text[i],charAt()andlengthuse code units; the iterator,codePointAt()(with manual stepping) andString.fromCodePoint()work with code points.
Browser support
Supported in all current browsers; string iteration arrived with ES2015.