escape string javascript code example

Example 1: javascript escape html

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

Example 2: js escape characters

JS Escape Characters
\' — Single quote
\" — Double quote
\\ — Backslash
\b — Backspace
\f — Form feed
\n — New line
\r — Carriage return
\t — Horizontal tabulator
WebsiteSetup.org - Beginner’s Javascript Cheat Sheet 7
\v — Vertical tabulator

Example 3: javascript escape single quote

document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";

Example 4: jquery escape html string

//escaping HTML with jquery
var dangerousHTML = "<script>alert('Badabing Baby!');</script>";
$("#myElementID").text(dangerousHTML); //.text() function will escape and display text


//Alternatively, here is plain Javascript escape function
function escapeHtml(str) {
    return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}

Example 5: escape in javascript

escape sequences in javascript
\' single quote
\" doucle quote
\\ backslash
\n newline
\r carriage return
\t tab
\b backspace
\f form feed