Last active
December 5, 2023 03:32
-
-
Save chen86860/adc5cb4af701e9df712de674947c4ba4 to your computer and use it in GitHub Desktop.
JavaScript String To Unicode/Unicode To String
This file contains 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
/** | |
* 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