在 HTML 中,某些字符是預留的。html
在 HTML 中不能使用小於號(<)和大於號(>),這是由於瀏覽器會誤認爲它們是標籤。瀏覽器
若是但願正確地顯示預留字符,咱們必須在 HTML 源代碼中使用字符實體。ide
如顯示小於號:.net
< 或 <
顯示結果 | 描述 | 實體名稱 | 實體編號 |
---|---|---|---|
空格 | |
  |
|
< | 小於號 | < |
< |
> | 大於號 | > |
> |
& | 與號 | & |
& |
" | 雙引號 | " |
" |
' | 單引號 | ' (IE不支持) |
' |
¢ | 分 | ¢ |
¢ |
£ | 鎊 | £ |
£ |
¥ | 日圓 | ¥ |
¥ |
§ | 節 | § |
§ |
© | 版權 | © |
© |
® | 註冊商標 | ® |
® |
× | 乘號 | × |
× |
÷ | 除號 | ÷ |
÷ |
更詳細的字符實體能夠看這裏 https://blog.csdn.net/QXXXD/article/details/111043532
/** * 把html轉義成HTML實體字符 * @param str * @returns {string} * @constructor */ 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字符 * @param str * @returns {string} * @constructor */ 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; } !