HTML特殊字符顯示(常用到的特殊符號,箭頭相關,貨幣相關,數學相關,標點,符號相關等)

HTML特殊符號編碼有很多種 unicode、十六進位碼(hex code),html 實體編碼(entity code),還有我們熟知的html 實體(html entity) ,爲了在css content屬性中使用,還有對應的 css code。

你可以在HTML標籤中直接插入十六進位碼(hex code),html 實體編碼(entity code)或者 html 實體(html entity)。在css content屬性中使用則應該使用對應的 css code。

需要特別注意的是:根據字體不同,部分符號顯示有所不同。

在項目應用中,有些時候需要將 html 和 html code進行轉換,這裏提供互轉的兩個方法:

JavaScript 代碼:

function html_encode(str)
{
  var s = "";
  if (str.length == 0) return "";
  s = str.replace(/&/g,"&");
  s = s.replace(/</g,"&lt;");
  s = s.replace(/>/g,"&gt;");
  s = s.replace(/ /g,"&nbsp;");
  s = s.replace(/\'/g,"&apos;");
  s = s.replace(/\"/g,"&quot;");
  s = s.replace(/\n/g,"<br>");
return s;
}
function html_decode(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(/&apos;/g,"\'");
  s = s.replace(/&quot;/g,"\"");
  s = s.replace(/<br>/g,"\n");
  return s;
}

使用DOM 的 innerHTML 和 textContent 也可以實現轉換,方法是動態創建一個容器標籤元素,如 DIV,將要轉換的字符串設置爲這個元素的 innerText,然後返回這個元素的 innerHTML,即得到經過 HTML 編碼轉換的字符串。

JavaScript 代碼:

function html_encode(html)
{
  return document.createElement('div')
  .appendChild(document.createTextNode(html))
  .parentNode.innerHTML;
}
 
function html_decode(html)
{
  var a = document.createElement('div');
  a.innerHTML = html;
  return a.textContent;
}

HTML Arrows 整理了大部分網站常用到的特殊符號,供大家參考使用:https://www.toptal.com/design...

如果你也是一個前端黨,無論是在學習前端開發,還是已經工作的,這裏推薦一下我們的前端q=u=n=:731771211,這裏是把夢想照亮的地方,同爲了生活而拼搏奮鬥,大家互相幫助。新手加入即可獲得經過整理的最前沿的前端技術資料,不定時更新技術,與企業需求同步。好友都在裏面交流,每天都會有大牛定時講解前端技術!知識改變命運

點擊:加入

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章