JavaScript Escape Quotes

How to Escape Single Quote and Special Characters in HTML and JavaScript

A JavaScript string consists of zero or more characters surrounded by quotes. JavaScript can misunderstand a literal quote enclosed inside single quotes, which is why the literal quote must be escaped with a backslash /. In this post, we are going to explore different JavaScript solutions to escape quotes and special characters.

JavaScript Escape Quotes - Example 1

var text = 'I hope we\'ll see you at the party next Saturday';
console.log( text ); //Results: "I hope we'll see you at the party next Saturday"

Same goes for double quotes:

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

When storing HTML representations within a String, special attention must be paid to escaping quotes, since HTML strings make extensive use of quotation marks in attributes, such as:

var html1 = "<p class=\"content\">I am going on holiday in June</p>"; // valid String
var html2 = '<p class="content">I\'d like to say "Hello"</p>'; // valid String

The characters &apos; (or &#39;) can also be used to represent single quotes in HTML strings, and &quot; (or &#34;) to represent double quotes.

var html1 = "<p class='content'>I'd like to say &quot;Hello&quot;</p>"; // valid String
var html2 = '<p class="content">I&apos;d like to say "Hello"</p>'; // valid String

Note: The use of &apos; and &quot; will not overwrite double quotes that browsers can automatically place on attribute quotes. 

JavaScript Escape Quotes - Example 2

<p aclass=content> Escape quotes in JavaScript <p class="content">, using &quot; can be misinterpreted by <p class=""content""> JavaScript \" or Html <p class="content">.

Using template literals (also known as template strings in previous ES6 editions) could be a helpful alternative if your string contains ' and ". Template literals do not require you to escape ' and ". Rather than single or double quotes, backticks (`) are used.

JavaScript Escape Quotes - Example 3

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

Wrapping Up: How to Escape Single Quote and Special Characters in HTML and JavaScript

One would not have thought that HTML had so many ways of expressing a single quotation!

Several solutions have been considered for the issue where a single quote breaks HTML.

When you need to use both single and double quotes in the string you can use the following solutions to escape the quotes:

  • " becomes &#34;
  • ' becomes &#39;

Keep in mind that you will never need to escape more than the following five special characters:

  • & becomes &amp;
  • < becomes &lt;
  •  becomes &gt; 
  • " becomes &#34;
  • ' becomes &#39;

Once you have these escaped you should never have an issue with broken values in HTML again.

Post a Comment

Previous Post Next Post