Try   HackMD

JavaScript Html格式轉換

tags: JavaScript

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
編譯結果怎麼不如預期?

當HTML渲染時,常常有資料需要顯示在畫面上,為何資料無法如預期顯示?

  1. 前端畫面處理並生成(Html, javascript)時,資料被HTML重新渲染
  2. 原HTML文本內已含有特殊符號,轉換成Web畫面即被視為HTML Tags

由於在HTML編譯過程中,許多文字/標點符號被視為 HTML Tags符號
導致特殊符號經過處理後,與原先樣子相差十萬八千里
因此在處理 javascript取值 上需要特別特別的注意、小心!


Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
特殊符號介紹

常用的符號使用如下表,若想要更了解可以點這

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
請點此

特殊符號
指定字元
代表意義
" " 雙引號
& & &記號
< &lt; 小於
> &gt; 大於
ˆ &circ; 進格修飾抑揚符
˜ &tilde; 小波浪符號
&ensp; 半格空格
&emsp; 全格空格
&ndash; 半格破折號
&euro; 歐元符號
© &copy; 版權符號
® &reg; 註冊商標
° &deg;

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
javascript 解碼 / 編碼 方法

萬一資料含有特殊符號需要顯示畫面上,可以使用javascript做預前處理

// encode 編碼 function encodeHTMLText(msgText){ let textarea = document.createElement("textarea"); textarea.innerText = msgText; return textarea.innerHTML; } // decode 解碼 function decodeHTMLText(msgText){ let textarea = document.createElement("textarea"); textarea.innerHTML = msgText.replace(/\r\n/g, "\\r\\n"); // 轉換換行符號 return textarea.value; } // ----------------------------------------------- // -------------------- Using -------------------- // ----------------------------------------------- var encodeText = "@$M>@#%JIsdfa<>" var decodeText = "&lt;?&gt;)JSOIHF(#@*%&amp;(@$(@)$#@D" > encodeHTMLText(encodeText) > '@$M&gt;@#%JIsdfa&lt;&gt;' > decodeHTMLText(decodeText) > '<?>)JSOIHF(#@*%&(@$(@)$#@D'

以上的 【編碼 / 解碼】可以製作成共用function
因為會遇到HTML特殊轉換符號的時機應該會有不少次 (?
在前端頁面塞入相對應資料,一旦資料被HTML編碼,就會變成不相同的資訊

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
經驗分享

網頁開發經常使用JS POST取得資訊,並不會發生 Encode/Decode 問題
但在使用 .NET MVC 開發後,有時需要預準備部分資訊在畫面上
結果網頁啟動後才發現文字全部被轉成亂碼,查詢問題發生來源
才知道HTML編譯時資料部分被自動轉換成HTML格式

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →


Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
連結