escape html function code example

Example 1: html escape characters

Escapes or unescapes an HTML file removing traces of offending characters that could be wrongfully interpreted as markup.

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 replaced with &gt;

Example 2: javascript escape html

function escapeHtml(str) {
    return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
}

Example 3: html escape function javascript

function escapeHTML(text) {  
    var replacements= {"<": "&lt;", ">": "&gt;","&": "&amp;", """: "&quot;"};                      
    return text.replace(/[<>&"]/g, function(character) {  
        return replacements[character];  
    }); 
}