JS and JQuery encode Html content and Html escape

  • 2021-07-22 08:29:11
  • OfStack

Without saying much, please look at the code:


 /** JQuery Html Encoding , Decoding 
*  The principle is to use JQuery Bring your own html() And text() Function can escape Html Character  
*  Virtual 1 A Div Get what you want by assigning and taking values Html Encoding or decoding  
*/ 
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> 
<script type="text/javascript"> 
//Html Code acquisition Html Escaped entity  
function htmlEncode(value){ 
 return $('<div/>').text(value).html(); 
} 
//Html Decoding acquisition Html Entity  
function htmlDecode(value){ 
 return $('<div/>').html(value).text(); 
} 
</script> 

<script type="text/javascript"> 
// Get Html Escape character  
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> 

// Code  
 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; 
 } 

Related articles: