关于html:html实体字符

2次阅读

共计 1094 个字符,预计需要花费 3 分钟才能阅读完成。

HTML 字符实体(character entities)

在 HTML 中,某些字符是预留的。

在 HTML 中不能应用小于号(<)和大于号(>),这是因为浏览器会误认为它们是标签。

如果心愿正确地显示预留字符,咱们必须在 HTML 源代码中应用字符实体。

如显示小于号:

&lt; 
或 
&#60;
  • 应用实体名而不是数字的益处是,名称易于记忆。
  • 害处是,浏览器兴许并不反对所有实体名称(对实体数字的反对却很好)。

罕用字符实体

显示后果 形容 实体名称 实体编号
空格 &nbsp; &#160;
< 小于号 &lt; &#60;
> 大于号 &gt; &#62;
& 与号 &amp; &#38;
双引号 &quot; &#34;
单引号 &apos;(IE 不反对) &#39;
&cent; &#162;
£ &pound; &#163;
¥ 日圆 &yen; &#165;
§ &sect; &#167;
© 版权 &copy; &#169;
® 注册商标 &reg; &#174;
× 乘号 &times; &#215;
÷ 除号 &divide; &#247;

更具体的字符实体能够看这里 https://blog.csdn.net/QXXXD/article/details/111043532

本义、反本义 HTML 实体字符

/**
 *  把 html 本义成 HTML 实体字符
 * @param str
 * @returns {string}
 * @constructor
 */
function htmlEncode(str) {
  var s = "";
  if (str.length === 0) {return "";}
  s = str.replace(/&/g, "&amp;");
  s = s.replace(/</g, "&lt;");
  s = s.replace(/>/g, "&gt;");
  s = s.replace(/ /g, "&nbsp;");
  s = s.replace(/\'/g,"&#39;");//IE 下不反对实体名称
  s = s.replace(/\"/g,"&quot;");
  return s;
}
/**
 *  转义字符还原成 html 字符
 * @param str
 * @returns {string}
 * @constructor
 */
function htmlRestore(str) {
  var s = "";
  if (str.length === 0) {return "";}
  s = str.replace(/&amp;/g, "&");
  s = s.replace(/&lt;/g, "<");
  s = s.replace(/&gt;/g, ">");
  s = s.replace(/&nbsp;/g, " ");
  s = s.replace(/&#39;/g, "\'");
  s = s.replace(/&quot;/g, "\"");
  return s;
}!
正文完
 0