Skip to content

Instantly share code, notes, and snippets.

@chen86860
Last active December 5, 2023 03:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chen86860/adc5cb4af701e9df712de674947c4ba4 to your computer and use it in GitHub Desktop.
Save chen86860/adc5cb4af701e9df712de674947c4ba4 to your computer and use it in GitHub Desktop.
JavaScript String To Unicode/Unicode To String
/**
* string to unicode
*/
const strToUnicode = (str) => {
return Array.from(str)
.map((char) => {
const codePoint = char.codePointAt(0);
// For code points less than 0xFFFF, use `padStart` to ensure that
// the code point is at least four characters in length, and pad with zeros at the front.
return codePoint > 0xffff ? `\\u{${codePoint.toString(16)}}` : `\\u${codePoint.toString(16).padStart(4, '0')}`;
})
.join('');
};
/**
* unicode to string
*/
const unicodeToStr = (unicodeStr) => {
return unicodeStr.replace(/\\u[0-9a-fA-F]{4}/g, (match) => {
return String.fromCodePoint(parseInt(match.replace(/\\u/, ''), 16));
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment