html字符实体和实体名称 < &lt;

 

防止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;
}

  

 

posted @ 2019-06-19 15:18  l_strive  阅读(601)  评论(0编辑  收藏  举报