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

Output:

$ node trim-utf8-string-to-bytes.js
input: abc😧🤕
0:	0	[]
1:	1	[61] a
2:	2	[6162] ab
3:	3	[616263] abc
4:	3	[616263] abc
5:	3	[616263] abc
6:	3	[616263] abc
7:	7	[616263f09f98a7] abc😧
8:	7	[616263f09f98a7] abc😧
9:	7	[616263f09f98a7] abc😧
10:	7	[616263f09f98a7] abc😧
11:	11	[616263f09f98a7f09fa495] abc😧🤕

@jthomerson
Copy link

Double semi-colon. Line 3. You’re welcome, first thing I saw. LOL 😂

@onebytegone
Copy link
Author

🤦‍♂️ Fixed.

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