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

1
2
3
4
5
6
7
8
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.

1
2
3
4
5
String.prototype.toUnicode = function () {
    return this.replace(/./g, function (char) {
        return "&#" + String.charCodeAt(char) + ";";
    });
};

Usage:
Call toUnicode() on any string object.

1
obj.toUnicode();

Example:

1
โ€œ<li/>โ€.toUnicode() //outputs: &#60;&#108;&#105;&#47;&#62;

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.

More Posts - Website

Follow Me:
Twitter