HTML escape

The following characters are reserved in HTML and must be replaced with their corresponding HTML entities:

  • " is replaced with "
  • & is replaced with &
  • < is replaced with &lt;
  • > is replaces with &gt;

The replace method of String is used to accomplish this. The regular expressions are used to find all matches in the text (if first parameter is string, then only first match will be replaced).

function escape(txt){
    return txt.replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/</g,'&lt;')
        .replace(/>/g, '&gt;');
 }
    
function unescape(txt){
    return txt.replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace( /&quot;/g, '"')
        .replace(/&amp;/g, '&');
}