Table of Contents
In this article, we will see how to escape quotes 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 learn javascript'; console.log(str); |
Output:
Ways to escape quotes 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 and \"
to escape double quotes.
Let’s see with the example:
Escape single quotes
1 2 3 4 |
var str='Let\'s learn 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 learn javascript"; console.log(str); |
Output:
Escape double quotes
1 2 3 4 |
var str='Let"s learn 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:
Escape quotes in Javascript in HTML context
If you need to escape quotes in HTML context, then you need to replace quotes with proper XML entity representation & quot;.
Please note that there should not be any space between & quot; here. I had to put a space because while rendering this page, wordpress was changing it to double quotes.
For example:
1 2 3 4 5 6 7 |
<html> <body> <a href="#" onclick="Calcalute('Assessment "Tax"'); return false;">calculate</a> </body> </html> |
Let’s say you want to escape quotes "Tax" here in onClick event string.
You need to replace double quotes with " here.
So your onclick string will be:
1 2 3 4 5 6 7 |
<html> <body> <a href="#" onclick="Calcalute('Assessment & quot;Tax& quot;'); return false;">calculate</a> </body> </html> |
Please note that there should not be any space between & quot; here. I had to put a space because while rendering this page, wordpress was changing it to double quotes.
That’s all about how to escape quotes in Javascript.