Created
November 13, 2017 13:27
-
-
Save AaronFlower/811a8e1f90fe0c921d0a6c0b31dfecce to your computer and use it in GitHub Desktop.
js escape html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 参考 https://github.com/janl/mustache.js/blob/b283da5c8c26dbf78c357a1f67bfed26d18f5e32/mustache.js#L60 | |
*/ | |
var entityMap = { | |
'&': '&', | |
'<': '<', | |
'>': '>', | |
'"': '"', | |
"'": ''', | |
'/': '/', | |
'`': '`', | |
'=': '=' | |
}; | |
/** | |
* HTML 字符进行转义。 | |
* eg: | |
* '<div>`print`, val() a = b<div>'.escapeHtml() | |
* "<div>`print`, val() a = b<div>" | |
*/ | |
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