Skip to content

Instantly share code, notes, and snippets.

@onebytegone
Last active September 27, 2019 01:42
Show Gist options
  • Save onebytegone/55f946f7ab53e4cecf99a9993fa32692 to your computer and use it in GitHub Desktop.
Save onebytegone/55f946f7ab53e4cecf99a9993fa32692 to your computer and use it in GitHub Desktop.
Function to trim UTF-8 string to a given number of bytes
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);
}
@onebytegone
Copy link
Author

🤦‍♂️ Fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment