Escaping quotes
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 ' (or ') as a single quote and " ( or ") as double quotes.
var hi = "<p class='special'>I'd like to say "Hi"</p>"; // valid String
var hello = '<p class="special">I'd like to say "Hi"</p>'; // valid String
Note: The use of '
and "
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 "
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`;