Javascript Tip: Convert string to unicode values

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:

  • ”.toUnicode() //outputs: <li/>

    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

  • Larry Battle

    I love to program, and discover new tech. Check out my stackoverflow and github accounts.

    View Comments

    Share
    Published by
    Larry Battle

    Recent Posts

    What really is Data Science? Told by a Data Scientist

    What REALLY is Data Science? Told by a Data Scientist - By Joma Tech

    7 years ago

    Video: How Water Towers Work

    How Water Towers Work - Practical Engineering

    7 years ago

    Dev Tip: Simple tips to improve code reviews

    Writing perfect code is a challenging process. That's where code reviews come in to help…

    7 years ago

    Video: How AI will change the 3d industry

    "The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"

    7 years ago

    Best Software Presentation for 2018

    "Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"

    7 years ago

    Dev Video: A Few Linux Shell Tips

    My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…

    7 years ago