English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Encoding and Escaping HTML Content with JavaScript and jQuery

Without further ado, please see the code:

 /** JQuery Html Encoding, Decoding 
* The principle is to use the built-in html() and text() functions of JQuery to escape HTML characters 
* Virtual a Div by assignment and retrieval to get the desired HTML encoding or decoding 
*/ 
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> 
<script type="text/javascript"> 
//Html encoding to get HTML escape entities 
function htmlEncode(value){ 
 return $('<div/>').text(value).html(); 
} 
//Html decoding to get HTML entities 
function htmlDecode(value){ 
 return $('<div/>').html(value).text(); 
} 
</script> 
<script type="text/javascript"> 
//Get HTML escape characters 
function htmlEncode( html ) {}} 
 return document.createElement( 'a' ).appendChild( 
  document.createTextNode( html ) ).parentNode.innerHTML; 
}; 
//Get Html 
function htmlDecode( html ) { 
 var a = document.createElement( 'a' ); a.innerHTML = html; 
 return a.textContent; 
}; 
</script> 
//Encoding 
 function html_encode(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, """); 
 s = s.replace(/\n/g, "<br>"); 
 return s; 
 } 
 //Decoding 
 function html_decode(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, "\""); 
 s = s.replace(/<br>/g, "\n"); 
 return s; 
 } 

That's all for this article. I hope the content of this article can bring you some help in learning or working, and I also hope to get more support for the Shout Tutorial!

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)