Skip to content

Instantly share code, notes, and snippets.

@flunder
Created September 4, 2023 09:29
Show Gist options
  • Save flunder/9e7c3618be4e5425ad14440c5cc0e1ee to your computer and use it in GitHub Desktop.
Save flunder/9e7c3618be4e5425ad14440c5cc0e1ee to your computer and use it in GitHub Desktop.
Shorten a string that contains emoticons.
function insertAt(string, subString, position) {
const before = string.substr(0, position);
const after = string.substr(position);
return `${before}${subString}${after}`;
}
/**
* Crude, but reliable way to do a substring with unicode chars. We tried other
* solutions but they don't work with the flags which are 4 code points!
*/
export default function unicodeSubstring(
string: string,
start: number,
end: number
): string {
const unicodeRegex = /[^\x00-\x7F]+/g; // Plus is important!
// Find all the unicode characters
const matches = [...string.matchAll(unicodeRegex)];
// Remove them all
const without = string.replace(unicodeRegex, '');
// Do the trim
const trimmed = without.substr(start, end);
// Re-insert the unicode characters which are in the substring
let withUnicode = trimmed;
for (let match of matches) {
const position = match.index ?? 0;
if (position >= start && position <= end) {
withUnicode = insertAt(withUnicode, match[0], match.index);
}
}
return withUnicode;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment