Table of Contents
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.
1 2 3 4 |
var str='Let's write javascript'; console.log(str); |
Output:
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
1 2 3 4 |
var str='Let\'s write javascript'; console.log(str); |
Output:
Escape double quotes
1 2 3 4 |
var str="Let\"s learn javascript"; console.log(str); |
Output:
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
1 2 3 4 |
var str="Let's write javascript"; console.log(str); |
Output:
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.
Let's learn javascript and write "Hello world"
;console.log(str);
Output:
As you can see, we have used single quotes and double quotes in same String and it just worked fine.
Further reading:
That’s all about how to escape Apostrophe in Javascript.