實現HTML編碼和解碼的JavaScript工具類
簡要教程
js-htmlencode是一款可以實現HTML編碼和解碼的JavaScript工具類。通過該JS工具類,你可以將HTML標簽轉換為對應的HTML實體,也能將HTML實體轉換回HTML標簽,非常實用。
安裝
可以通過bower或npm來安裝js-htmlencode插件。
bower install js-htmlencode npm install js-htmlencode
使用方法
在頁面中引入htmlencode.js文件,如何你可以像下面這樣使用該HTML編碼和解碼插件。
htmlEncode('需要進行編碼的HTML文本'); htmlDecode('需要進行解碼的字符串');
如果你使用node.js,你可以:
htmlEncode = require('js-htmlencode');
或者:
htmlEncode = require('js-htmlencode').htmlEncode; htmlDecode = require('js-htmlencode').htmlDecode;
應用舉例
下面是一些小例子。
代碼:
htmlEncode('<a href="#">HTML Encode</a>'); htmlDecode('<a href="#">HTML Encode</a>'); htmlDecode('<a href="#">HTML Encode</a>');
上面的代碼的輸出結果為:
<a href="#">HTML Encode</a> <a href="#">HTML Encode</a> <a href="#">HTML Encode</a>
擴展
jQuery
如果你使用jQuery,可以使用下面的代碼來添加一個jQuery擴展。
jQuery.htmlEncode = htmlEncode jQuery.htmlDecode = htmlDecode
然后你就可以像下面這樣來進行編碼和解碼:
$.htmlEncode('<a href="#">HTML Encode</a>'); $.htmlDecode('<a href="#">HTML Encode</a>');
Prototype
你還可以直接在原型prototype中添加擴展。
String.prototype.htmlEncode = function() { return htmlEncode(this); }; String.prototype.htmlDecode = function() { return htmlDecode(this); };
然后你就可以像下面這樣來進行編碼和解碼:
'<a href="#">HTML Encode</a>'.htmlEncode(); '<a href="#">HTML Encode</a>'.htmlDecode();
該HTML編碼和解碼插件的github地址為: https://github.com/emn178/js-htmlencode
來源:jQuery之家
本文由用戶 4528krkj 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!