Escape Apostrophe in JavaScript

In this article, we will see how to escape Apostrophe in JavaScript.

Let’s see what happens if we have singe quote in String and we also use single quotes to declare the string in JavaScript.

Output:

unknown: Unexpected token (1:26)

Ways to escape Apostrophe in JavaScript

There are multiple ways to escape quotes in JavaScript. Let’s go through each of them.

Using escape character

You can use escape character backslash(\) to escape quotes in Javascript. It will prevent javascript to interpret end of String.

You can use \' to escape single quotes.

Let’s see with the example:
Escape Apostrophe

Output:

Let’s write javascript

Escape double quotes

Output:

Let”s learn javascript

Using alternate String syntax

You can use opposite string syntax of the one you are currently having.

For example:
If you have single quotes in String, then you can define String in double quotes. Similarly, in case you have double quotes in String, then you can define String in single quotes.
Let’s see with the example:
Escape single quotes

Output:

Let’s write javascript

Using template literals

Template literals use back ticks(`) rather than quotes to define String. With template literals, you can use both single quotes and double quotes inside a String, so you don;t have to escape quotes in String.

var str=Let's learn javascript and write "Hello world";
console.log(str);

Output:

Let’s learn javascript and write “Hello world”

As you can see, we have used single quotes and double quotes in same String and it just worked fine.

That’s all about how to escape Apostrophe in Javascript.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *