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}
. Theu
flag enables Unicode support. - This matches characters by code points as well.
- The RegEx supplied matches any character
- 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?