The following script will convert a string to the unicode values using javascript.
toUnicode is a extension to String.charCodeAt. The benefit of this function is that it returns the whole string a html unicode format.
Code
String.prototype.toUnicode = function () {
var uni = [],
i = this.length;
while (i--) {
uni[i] = this.charCodeAt(i);
}
return "" + uni.join(';') + ";";
};
Here’s another method that I thought of.
This one is using a regexp instead of a while loop and an array to form the unicode text.
String.prototype.toUnicode = function () {
return this.replace(/./g, function (char) {
return "" + String.charCodeAt(char) + ";";
});
};
Usage:
Call toUnicode() on any string object.
obj.toUnicode();
Example:
“However, if possible use document.createTextNode to insert text instead of converting it to unicode. Document.createTextNode is a native DOM method meaning it’s a lot faster, and easier to understand .
More infor here: document.createTextNode
What REALLY is Data Science? Told by a Data Scientist - By Joma Tech
Writing perfect code is a challenging process. That's where code reviews come in to help…
"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"
"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"
My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…
View Comments
Alternative link:
http://buildingonmud.blogspot.com/2009/06/convert-string-to-unicode-in-javascript.html
Nice solution :)
Keep Coding
Thanks for this solution, This fixed a submission form that sent the contents to email. The submission form will be filled out in over 15 different languages, and this will 'translate'/encode them to english for the email client
So much has changed since 2009. I would suggest using a library dedicated to this task.
Check this out: https://github.com/bestiejs/punycode.js