Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow to use escape characters to correctly log quotes in a string...

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

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, with no difference.

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

Javascript




// 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


Output:

true
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.

Javascript




// 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'"


Output:

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

RELATED ARTICLES

Most Popular

Recent Comments