JavaScript Strings Escaping quotes

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


If your string is enclosed (i.e.) in single quotes you need to escape the inner literal quote with backslash \

var text = 'L\'albero means tree in Italian';
console.log( text ); \\ "L'albero means tree in Italian"

Same goes for double quotes:

var text = "I feel \"high\"";

Special attention must be given to escaping quotes if you're storing HTML representations within a String, since HTML strings make large use of quotations i.e. in attributes:

var content = "<p class=\"special\">Hello World!</p>";        // valid String
var hello   = '<p class="special">I\'d like to say "Hi"</p>'; // valid String

Quotes in HTML strings can also be represented using &apos; (or &#39;) as a single quote and &quot; ( or &#34;) as double quotes.

var hi    = "<p class='special'>I'd like to say &quot;Hi&quot;</p>"; // valid String
var hello = '<p class="special">I&apos;d like to say "Hi"</p>';      // valid String

Note: The use of &apos; and &quot; will not overwrite double quotes that browsers can automatically place on attribute quotes. For example <p class=special> being made to <p class="special">, using &quot; can lead to <p class=""special""> where \" will be <p class="special">.


If a string has ' and " you may want to consider using template literals (also known as template strings in previous ES6 editions), which do not require you to escape ' and ". These use backticks (`) instead of single or double quotes.

var x = `"Escaping " and ' can become very annoying`;

Got any JavaScript Question?