Iterators

Micro Blog
Micro Blog in JavaScript
let string = 'πŸ‘¨β€πŸ‘¨β€πŸ‘§β€πŸ‘§πŸ’œπŸ€§πŸ€’πŸ₯πŸ˜€';
let string2 = 'The quick brown fox jumps over the lazy dog. It barked.';

const splitWithIterator = (s) => [...s].slice(0, 5).join('');

console.log(splitWithIterator(string)); // will be "πŸ‘¨β€πŸ‘¨β€πŸ‘§" - incorrect
console.log(splitWithIterator(string2)); // will be "‍The q"

This solution:

  • Uses spread syntax to unpack the string into an array of its characters.
    • internaly, the spread operator works with iterators to separate the string by its code points.
  • Then it separates the first 5 characters (code points).
  • Finally, it joins them back into a string.
Note

This approach will not yield the correct result when applied to characters that are made of multiple graphere clusters and are meant to represent a single visual unit, such as some emoji.

26th Apr 2025 · Found it useful?