Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
HTMLEncode method for javascript
String.prototype.HTMLEncode = function (str) {
var result = "";
var str = (arguments.length === 1) ? str : this;
for (var i = 0; i < str.length; i++) {
var chrcode = str.charCodeAt(i);
result += (chrcode > 128) ? "&#" + chrcode + ";" : str.substr(i, 1)
}
return result;
}
@netsi1964

This comment has been minimized.

Copy link
Owner Author

commented Apr 12, 2015

These 9 lines of javascript code will extend the String object with a new method:

Used as a method on a string

var hasUTF8Chars = "æøå›˘˚≥•±≈";
console.log(hasUTF8Chars.HTMLEncode());
// => &#63743;&#230;&#248;&#229;&#8250;&#728;&#730;&#8805;&#8226;&#177;&#8776;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.