Created
March 26, 2018 09:22
-
-
Save NejcZdovc/447d730e0aada3771da7b88804d010f2 to your computer and use it in GitHub Desktop.
String to Uint8Array
This file contains hidden or 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
// source https://coolaj86.com/articles/unicode-string-to-a-utf-8-typed-array-buffer-in-javascript/ | |
'use strict'; | |
// string to uint array | |
function unicodeStringToTypedArray(s) { | |
var escstr = encodeURIComponent(s); | |
var binstr = escstr.replace(/%([0-9A-F]{2})/g, function(match, p1) { | |
return String.fromCharCode('0x' + p1); | |
}); | |
var ua = new Uint8Array(binstr.length); | |
Array.prototype.forEach.call(binstr, function (ch, i) { | |
ua[i] = ch.charCodeAt(0); | |
}); | |
return ua; | |
} | |
unicodeStringToTypedArray('test') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment