How to use escape characters to correctly log quotes in a string using JavaScript ?
Escape Characters are the symbols 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
We can print quotes in the console using single and double quotes 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: In this example, we will print single and double quotes in the console.
Javascript
let s1 = 'Geeks for Geeks' ;
let s2 = "Geeks for Geeks" ;
console.log((s1 === s2));
console.log(s1);
console.log(s2);
let str = '"Geeks" "FOR" Geeks' ;
console.log(str);
str = "'Geeks' \'FOR\' Geeks" ;
console.log(str);
|
Output
true
Geeks for Geeks
Geeks for Geeks
"Geeks" "FOR" Geeks
'Geeks' 'FOR' Geeks
For double quotes
We are using \” for printing the double quotes in the console.
Example: Using escape sequences – If you have begun the quotes using \’ then you must end the quote also using \’ and vice versa.
Javascript
let str = 'Geeks \'FOR\' Geeks' ;
console.log(str);
str = "Geeks \"FOR\" Geeks" ;
console.log(str);
str = '\'Geeks \"FOR\" Geeks\'' ;
console.log(str);
str = "\ "\"Geeks\" for \"Geeks\" is \'the\' best \'platform\'\"" ;
console.log(str);
|
Output
Geeks 'FOR' Geeks
Geeks "FOR" Geeks
'Geeks "FOR" Geeks'
""Geeks" for "Geeks" is 'the' best 'platform'"
Last Updated :
08 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...