VOOZH about

URL: https://www.geeksforgeeks.org/javascript/how-to-use-escape-characters-to-correctly-log-quotes-in-a-string-using-javascript/

⇱ How to use Escape Characters to Log Quotes in JavaScript? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to use Escape Characters to Log Quotes in JavaScript?

Last Updated : 9 Sep, 2024

In JavaScript, escape characters are used to include special characters like quotes within strings without causing syntax errors.

By placing a backslash (`\`) before a quote, you can ensure that the quote is treated as part of the string rather than as a delimiter. This is essential for correctly logging strings that contain both single and double quotes.

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:

Using Quotes Without Escaping Characters

In JavaScript, you can use single quotes to define a string and include double quotes inside it without needing escape characters. This allows you to easily print double quotes within the string while avoiding syntax errors.

Example: In this example, string literals using single and double quotes. It compares strings for equality and shows how to include quotes inside strings using escaping or different quote types.


Output
true
Geeks for Geeks
Geeks for Geeks
"Geeks" "FOR" Geeks
'Geeks' 'FOR' Geeks

Using Escape Characters for Double Quotes

In JavaScript, you can use double quotes to define a string and include single quotes inside it without needing escape characters. This approach allows you to print single quotes within the string seamlessly while maintaining correct syntax.

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


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