Convert to UCS2 and from UCS2 in JavaScript
You can use the next function for encoding a simple string to UCS2
:
function toUCS2(code) {
function toPaddedHexString(num, len) {
const str = num.toString(16).toUpperCase();
return '0'.repeat(len - str.length) + str;
}
const hexers = punycode.ucs2.decode(code);
let ucs2str = '';
hexers.forEach((i) => {
ucs2str += toPaddedHexString(i, 4);
});
return ucs2str;
}
Example:
console.log(toUCS2('*123#')); // '002A0031003200330023'
You can use next function for decoding from UCS2
:
function fromUCS2(code) {
const txt_codes = code.match(/.{1,4}/g);
let codes = [];
txt_codes.forEach((i) => {
codes.push(parseInt(i, 16));
});
return punycode.ucs2.encode(codes);
}
Example:
console.log(fromUCS2('002A0031003200330023')); // '*123#'
You need punycode
package for both (use npm install punycode
or include as js
file).
const punycode = require('punycode');