Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

String Length

To determine the length of a string, utilize the built-in length property.

Example

let text = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
let length = text.length;

Escape Characters

Since strings must be enclosed in quotes, JavaScript will misinterpret this string:

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

The phrase will be shortened to “We are the so-called.”

To address this issue, you can utilize a backslash escape character.

The backslash (\) converts special characters into regular string characters.

 

Code

Result

Description

\’

Single quote

\”

Double quote

\\

\

Backslash

Examples

The sequence ” adds a double quote within a string.

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

The sequence ‘ places a single quote inside a string.

let text= ‘It\’s alright.’;

The sequence \ adds a backslash into a string.

let text = “The character \\ is called backslash.”;

There are six additional escape sequences that are valid in JavaScript.

Code

Result

\b

Backspace

\f

Form Feed

\n

New Line

\r

Carriage Return

\t

Horizontal Tabulator

\v

Vertical Tabulator

Note: The six escape characters mentioned above were originally created for controlling typewriters, teletypes, and fax machines, and they are not relevant in HTML.

Breaking Long Lines

To enhance readability, programmers often prefer to avoid long lines of code.

A safe method for breaking up a statement is to do so after an operator.

Example

document.getElementById(“demo”).innerHTML =
“Hello Dolly!”;

A reliable method for splitting a string is by using string concatenation.

Example

document.getElementById(“demo”).innerHTML = “Hello “ +
“Dolly!”;

Template Strings

Templates were introduced in ES6 (JavaScript 2016).

They are strings wrapped in backticks (e.g., This is a template string) and enable the creation of multiline strings.

Example

let text =
`The quick
brown fox
jumps over
the lazy dog`
;

Note

Templates are not compatible with Internet Explorer.