JavaScript Coder

How to escape double qoutes in a string

javascript quotes in string javascript escape quotes in string

There are many different ways to escape quotes in a string. This article will show each one.

Escaping string literals

If you just want to escape string literals, here are the ways to do it.
There are at least three ways to create a string literal in Javascript - using single quotes, double quotes, or the backtick ( ).
So, if you enclose your string in single quotes, no need to escape double quotes and vis versa.

const simpleString='"It is working", he said.';

const anotherString="Wait, I'm coming too. Said she."

You can escape double quotes (or any special character) using a slash ( \ )

const slashEscape="It was the last step.\"Stop!\". She shouted."

Inside a template literal, you don’t have to escape single or double-quotes.

const templateLiteral=`"I'm OK with this Agreement" 
Said he.
"Me too!".
I said.`

Try this code:

See the Pen Javascript escape quotes in literals

Function to escape a string

Suppose you received a string that may contain quotes and other special characters. You can use JSON.stringify() to escape the special characters like so:

function escapeString(str)
{
  return JSON.stringify(str)
}

Here is an example:

See the Pen Javascript Escape String Function