how to escape characters in 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: js json escape

JSON.parse(JSON.stringify(jsonObject));

Example 4: javascript have special characters

var format = /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
//            ^                                       ^   
document.write(format.test("My@string-with(some%text)") + "<br/>");
document.write(format.test("My string with spaces") + "<br/>");
document.write(format.test("MyStringContainingNoSpecialChars"));

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

Tags:

Html Example