Skip to content

Instantly share code, notes, and snippets.

@AaronFlower
Created November 13, 2017 13:27
Show Gist options
  • Save AaronFlower/811a8e1f90fe0c921d0a6c0b31dfecce to your computer and use it in GitHub Desktop.
Save AaronFlower/811a8e1f90fe0c921d0a6c0b31dfecce to your computer and use it in GitHub Desktop.
js escape html
/**
* 参考 https://github.com/janl/mustache.js/blob/b283da5c8c26dbf78c357a1f67bfed26d18f5e32/mustache.js#L60
*/
var entityMap = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
'/': '&#x2F;',
'`': '&#x60;',
'=': '&#x3D;'
};
/**
* HTML 字符进行转义。
* eg:
* '<div>`print`, val() a = b<div>'.escapeHtml()
* "&lt;div&gt;&#x60;print&#x60;, val() a &#x3D; b&lt;div&gt;"
*/
String.prototype.escapeHtml = function() {
return this.replace(/[&<>"'`=\/]/g, function (s) {
return entityMap[s];
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment