Last active
September 27, 2019 01:42
-
-
Save onebytegone/55f946f7ab53e4cecf99a9993fa32692 to your computer and use it in GitHub Desktop.
Function to trim UTF-8 string to a given number of bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { StringDecoder } = require('string_decoder'), | |
input = 'abc😧🤕', | |
length = Buffer.byteLength(input); | |
function trimToSize(str, byteLength) { | |
const decoder = new StringDecoder('utf8'), | |
buffer = new Buffer(str); | |
return decoder.write(buffer.slice(0, byteLength)); | |
} | |
console.log('input:', input); | |
for (var i = 0; i <= length; i++) { | |
const result = trimToSize(input, i); | |
console.log(`${i}:\t${Buffer.byteLength(result)}\t[${Buffer.from(result).toString('hex')}]`, result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Double semi-colon. Line 3. You’re welcome, first thing I saw. LOL 😂