How to Escape Quotes in JavaScript

Anika Tabassum Era Feb 02, 2024
  1. Use of Escape Quote (\" and \') in JavaScript
  2. Use Entity Characters as Escape Quote in JavaScript
How to Escape Quotes in JavaScript

In JavaScript, while defining a string, we use quotation (" ") as the boundary of the context. Often we use the apostrophe(' ') to do a similar task. The problem pops up when we have one of these characters in our context. Automatically, when the webpage is displayed some of the contexts get chopped off.

So, for solving this problem, we use \", \', \\, and many more escape quotes. Along with these, we also prefer some XML special character code to define such symbols, such as ", '.

In the next section, we will demonstrate the cases with some code examples.

Use of Escape Quote (\" and \') in JavaScript

Here, when we define the string with " " it will not be operated if there’s is any quotation in the inner context. However, the solution says to use a backslash before the quotation, part of the context. But in this case, you have an apostrophe amidst the context, it will work fine.

Code Snippet:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>test</title>
</head>
<body>
<p id="okay"></p>
</body>
</html>
var x = 'I\'m cool.';
var y = 'Hey! It\'s "Nelson"!';
var z = 'The board has a "Cross" sign.';


document.getElementById('okay').innerHTML = x + '<br>' + y + '<br>' + z;

Output:

escape quotes in javascript

As you can see, whenever we use " " for strings, the quotation inside the string needs a backslash. Again, when the string is wrapped by the ' ' then any inner apostrophe will have a backslash just before the sign.

Use Entity Characters as Escape Quote in JavaScript

Entity characters of HTML also work like escape quotes. The convention requires a&quot; for one quotation mark and a &apos; for displaying one apostrophe.

Code Snippet:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>test</title>
</head>
<body>
<p id="okay"></p>
</body>
</html>
var a1 = 'Hey, would you mind saying &quot;Hi&quot;?';
var a2 = 'Okay! &apos;Hello&apos;';

document.getElementById('okay').innerHTML = a1 + '<br>' + a2;

Output:

escape quotes in javascript

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook