JS Strings

You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

Example

let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';

String Length

To find the length of a string, use the built-in length property:

Example

let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
text.length;    // Will return 26


Escape Character

Because strings must be written within quotes, JavaScript will misunderstand this string:

let text = "We are the so-called "Vikings" from the north.";

The string will be chopped to "We are the so-called ".

The solution to avoid this problem, is to use the backslash escape character.

The backslash (\) escape character turns special characters into string characters:

Code Result Description
\' ' Single quote
\" " Double quote
\\ \ Backslash

The sequence \"  inserts a double quote in a string:

Example

let text = "We are the so-called \"Vikings\" from the north.";

The sequence \'  inserts a single quote in a string:

Example

let text= 'It\'s alright.';

The sequence \\  inserts a backslash in a string:

Example

let text = "The character \\ is called backslash.";

Six other escape sequences are valid in JavaScript:

Code Result
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tabulator
\v Vertical Tabulator