Intl.Segmenter

Micro Blog
Micro Blog in JavaScript
let string = '๐Ÿ‘จโ€๐Ÿ‘จโ€๐Ÿ‘งโ€๐Ÿ‘ง๐Ÿ’œ๐Ÿคง๐Ÿค’๐Ÿฅ๐Ÿ˜€';

const splitWithSegmenter = (s) =>
  Array.from(new Intl.Segmenter().segment(String(s)), (x) => x.segment)
    .slice(0, 5)
    .join('');

console.log(splitWithSegmenter(string)); // will be "๐Ÿ‘จโ€๐Ÿ‘จโ€๐Ÿ‘งโ€๐Ÿ‘ง๐Ÿ’œ๐Ÿคง๐Ÿค’๐Ÿฅ" - correct, yay!

This solution:

  • Uses the Intl.Segmenter object to split the string by graphemes and form an array from the result.
  • Then it separates the first 5 graphemes.
  • Finally, it joins them back into a string.
Note

At the time of writing (February 2024) this method is not fully supported by the stable release of the Mozilla Firefox browser. However, support for the Intl.Segmenter object is being worked on in the Nightly release of the browser.

26th Apr 2025 · Found it useful?