Regex

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

const splitWithRegEx = (s) => s.match(/.{0,5}/gu)[0];

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

This solution:

  • Uses the String.match() method with a supplied RegEx
    • The RegEx supplied matches any character ., between 0 and 5 times {0, 5}. The u flag enables Unicode support.
    • This matches characters by code points as well.
  • Then it returns the first match as the output 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?