JavaScript Strings


JavaScript strings help store and handle text.

Using Quotes

A JavaScript string is a bunch of letters or symbols that you put inside quotation marks.

You can use single or double quotes:


Quotes Inside Quotes

You can include quotation marks within a text, as long as they differ from the quotation marks enclosing the text.


String Length

To determine the size of a text, utilize the included length property:


Escape Character

JavaScript gets confused when it encounters a string that isn't enclosed in quotation marks. Here's an example:

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

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

To prevent this issue, you can use a special character called the backslash escape character.

The backslash (\) escape character changes special characters into regular characters in a string.

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

The code \" adds a double quote to a string.

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

The sequence \\  inserts a backslash in a string:

JavaScript allows for six different escape sequences to be used:

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

The six escape characters mentioned were initially made to operate typewriters, teletypes, and fax machines. However, they aren't relevant in HTML.


Breaking Long Code Lines

To make code easy to read, programmers usually prefer to keep lines of code shorter than 80 characters.

If a JavaScript command is too long to fit on one line, it's a good idea to split it into two lines, and the best spot to do that is right after an operator.

A good way to split a string is by adding strings together.


Template Strings

Templates came out with ES6 (JavaScript 2016).

Templates are words or phrases surrounded by backticks, like this: (`This is a template string`).

Templates make it possible to write multiple lines of text together.


JavaScript Strings as Objects

Usually, JavaScript strings are basic values made from literals:

let x = "John";

But strings can also be defined as objects with the keyword new:

let y = new String("John");

Do not create Strings objects.

The use of the new keyword can make code more complex and slow down execution.

String objects can produce unexpected results:

Note : the difference between (x==y) and (x===y).

Comparing two JavaScript objects always returns false.