JavaScript: Inserting Special Characters (and Emojis) in the Strings
Well, this time, we'll go beyond the book.
We want to insert a special character into the JavaScript String.
Below is the code, and some explanation after that.
const someText = "Copyright Sign: \u00A9";
console.log(someText); // Copyright ©
Alright, \u00A9
can be divided into two parts.
\u
is for Unicode, it says that the text following that is in Unicode format.
00A9
is the Unicode for the copyright symbol.
So, first, we tell the JavaScript engine that we will have some Unicode characters coming up, and then we come up with the Unicode characters.
We want to insert an emoji into the JavaScript Strings.
const message = "Sometimes restarting the computer fixes the bug " + String.fromCodePoint(0x0001F601);
console.log(message);
// Sometimes restarting the computer fixes the bug 😁
Mostly the same thing happening here too. Except, we are not using Unicode this time. We're using the UTF-32 encoding.
For that emoji, the UTF-32 encoding is 0x0001F601
.
And we use String.fromCodePoint method to format that encoding. And finally, it prints that emoji in the console.
Cool?
The good thing is, you don't need to memorize anything, just search it on the internet, maybe see the docs.
Bookmark this example if you want, so you won't have to search.