html字符实体和实体名称 < <
防止XSS注入,需要将内容过滤存储:
/** * 把html转义成HTML实体字符 */ function htmlEncode(str) { var s = ""; if (str.length === 0) { return ""; } s = str.replace(/&/g, "&"); s = s.replace(/</g, "<"); s = s.replace(/>/g, ">"); s = s.replace(/ /g, " "); s = s.replace(/\'/g, "'");//IE下不支持实体名称 s = s.replace(/\"/g, """); return s; } /** * 转义字符还原成html字符 */ function htmlRestore(str) { var s = ""; if (str.length === 0) { return ""; } s = str.replace(/&/g, "&"); s = s.replace(/</g, "<"); s = s.replace(/>/g, ">"); s = s.replace(/ /g, " "); s = s.replace(/'/g, "\'"); s = s.replace(/"/g, "\""); return s; }