Skip to content
Related Articles
Open in App
Not now

Related Articles

How to use escape characters to correctly log quotes in a string using JavaScript ?

Improve Article
Save Article
  • Difficulty Level : Expert
  • Last Updated : 06 Jan, 2023
Improve Article
Save Article

Escape Characters are the symbol used to begin an escape command in order to execute some operation. They are characters that can be interpreted in some alternate way than what we intended to. Javascript uses ‘\‘ (backslash) in front as an escape character.

Our aim is that we want to print in the console like:

""Geeks" for "Geeks" is 'the' best 'platform'"

To print quotes, using escape characters we have two options:

  • For single quotes:  \’  (backslash followed by single quote)
  • For double quotes: \”  (backslash followed by double quotes)

We can print quotes in the console using single and double quotes also without using escape characters. But there is a restriction we can either print only single or double-quotes. If the string is represented in single quotes then we can print only double quotes, and if the string is represented as single quotes then we can print double quotes inside it. Strings represented in single or double quotes are the same, no difference.

Example: In this example, we will print single and double quotes in the console.


    // Using single quotes for string
    let s1 = 'Geeks for Geeks';
    // Using double quotes for string
    let s2 = "Geeks for Geeks";
    // Both s1 and s2 are same
    console.log((s1 === s2)); // true
    console.log(s1); // Geeks for Geeks
    console.log(s2); // Geeks for Geeks
    // Using single quotes to represent string
    // and double to represent quotes inside
    // string
    let str = '"Geeks" "FOR" Geeks';
    console.log(str); // "Geeks" "FOR" Geeks
    // Using double quotes to represent string
    // and single to represent quotes in string
    str = "'Geeks' 'FOR' Geeks";
    console.log(str); // 'Geeks' 'FOR' Geeks


Geeks for Geeks
Geeks for Geeks
"Geeks" "FOR" Geeks
'Geeks' 'FOR' Geeks

Example 2: Using escape sequences – If you have begun the quotes using \’ then you must end the quote also using \’ and vice versa.


    // Using escape sequences - here you can
    // use single as well as double quotes
    // within the string to print quotation
    let str = 'Geeks \'FOR\' Geeks';
    console.log(str); // Geeks 'FOR' Geeks
    str = "Geeks \"FOR\" Geeks";
    console.log(str); // Geeks "FOR" Geeks
    str = '\'Geeks \"FOR\" Geeks\'';
    console.log(str); // 'Geeks "FOR" Geeks'
    str = "\"\"Geeks\" for \"Geeks\" is \'the\' best \'platform\'\"";
    console.log(str); // ""Geeks" for "Geeks" is 'the' best 'platform'"


Geeks 'FOR' Geeks
Geeks "FOR" Geeks
'Geeks "FOR" Geeks'
""Geeks" for "Geeks" is 'the' best 'platform'"

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!