-
Javascript Tip: Convert string to unicode values
Posted on October 30th, 2009 1 commentThe 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.
String.prototype.toUnicode = function() {
var uni = [],
i = this.length;
while (i--) {
uni[i] = this.charCodeAt(i);
}
return "&#" + uni.join( ';&#' ) + ";";
};
Usage: obj.toUnicode();
Example: “<li/>”.toUnicode() //outputs: <li/>
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) + ";";
});
};
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
Bad Behavior has blocked 14 access attempts in the last 7 days.



Recent Comments