DEV Community

Akhil sai
Akhil sai

Posted on

Quick tip: How to show the literal quotes " or ' in a string in javascript

Generally we declare a string in javascript as follows

var str1 = "Hello there!";
//or
var str2 = 'Hello there!';

There can be use cases when you need to include a double quote or a single quote inside the string.

To achieve this, we can use the escape character '\' as shown below

var str1 = "\"Hello there!\"- Obi Wan Kenobi";
// "Hello there" - Obi Wan Kenobi
var str2 = '\'Urr Arrgghh Urr\' - Chewbacca' 
// 'Urr Arrgghh Urr'- Chewbacca

Bonus Content

How to display '\' in string since '\' is considered as escape sequence? Even in this case, the escape sequence can be used to display '\'

var str3 = "1\\2 is perfectly balanced";
/* 1\2 is perfectly balanced */

For more details on string and escape characters refer: MDN Docs

Hope you find it useful!

Top comments (0)