Skip to content

Instantly share code, notes, and snippets.

@romellem
romellem / unicode-slice.js
Last active April 22, 2026 18:24
JS String Slice - UTF-8, UTF-16, UTF-32, and Graphemes
function utf16slice(str, start, end) {
// UTF-16 code units - same as native
return str.slice(start, end);
}
function utf8slice(str, start, end) {
// UTF-8 bytes; slicing mid-codepoint yields U+FFFD
const bytes = new TextEncoder().encode(str);
return new TextDecoder().decode(bytes.slice(start, end));
}