New Lines, Quotes and Escape Characters · JavaScript
Ch 2 · Your First JavaScript Program — card 3 of 3.
- How \n puts a line break inside a message
- How to show quote marks inside a piece of text
- What the backslash does and how to print one
Sometimes the text you want to show contains characters that JavaScript would normally treat as code. A quote mark is the classic problem: in "She said "hi"" JavaScript thinks the text ends at the second quote mark, and the program fails with an error. There are two fixes. You can wrap the text in the other kind of quote, so single quotes on the outside can hold double quotes on the inside, and the other way round. Or you can put a backslash \ in front of the quote mark. The backslash is called an escape character: it tells JavaScript "treat the next character as ordinary text". The same idea gives you \n, which starts a new line, and \\, which prints a single backslash.
// \n starts a new line inside a string
console.log("Roses are red\nViolets are blue");
// Use one kind of quote outside, the other inside
console.log("It's time to code!");
console.log('She said "hello" to the class.');
// Or put a backslash before the quote to "escape" it
console.log("She said \"hello\" again.");
console.log('It\'s working!');
// \\ prints a single backslash
console.log("C:\\Users\\student");- Text in JavaScript can use single or double quotes, as long as they match
- A backslash changes the meaning of the character after it
- An escaping backslash never appears in the output, so write \\ when you need a real one