In JavaScript, escaping literal quotes is essential when you want to include quotes within a string. The way you escape quotes depends on the type of quotes you are using to define the string.
1. Single-Quoted Strings ('...')
Use a backslash (\) before the single quote to escape it.
Example
const singleQuoteString = 'It\'s a beautiful day!';
2. Double-Quoted Strings ("...")
Use a backslash (\) before the double quote to escape it.
Example
const doubleQuoteString = "He said, \"Hello, world!\"";
3. Backtick Strings (Template Literals)
Use a backslash before the backtick to escape it.
const backtickString = `She said, \`Welcome to JavaScript!\``;
escapeQuotes.js
const singleQuoteString = 'It\'s a beautiful day!'; console.log(singleQuoteString); // Output: It's a beautiful day! const doubleQuoteString = "He said, \"Hello, world!\""; console.log(doubleQuoteString); // Output: He said, "Hello, world!" const backtickString = `She said, \`Welcome to JavaScript!\``; console.log(backtickString); // Output: She said, `Welcome to JavaScript!`
Output
It's a beautiful day! He said, "Hello, world!" She said, `Welcome to JavaScript!`
These escape sequences allow you to include the same type of quote within your string without causing syntax errors.
No comments:
Post a Comment