Skip to content

Instantly share code, notes, and snippets.

@netsi1964
Created April 12, 2015 06:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save netsi1964/fcc8c0c6f1330d666372 to your computer and use it in GitHub Desktop.
Save netsi1964/fcc8c0c6f1330d666372 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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