JS: String Overview

By Xah Lee. Date: . Last updated: .

Literal String Expression

Use double quote or single quote for string. There's basically no difference between the two.

const s1 = "Mary's cat";
// double quote

const s2 = 'Mary\'s cat';
// single quote, with escape

Use \n for newline.

// use \n for newline
const ss = "cat\ndog";

console.log(ss); // prints 2 lines

Literal newline in string is not allowed. Use backslash to continue a line.

// illegal syntax. Literal newline is not allowed
const s = "a

// use backslash to continue a line
const s = "c\

console.log(s); // prints cd

Template String

String can also be quoted by using GRAVE ACCENT `, like this:

let x = `something`;

Expression of the form ${expression} in template string is evaluated.

console.log ( `I have ${1 + 1} cats` );
// I have 2 cats

[see JS: Template String]

String is Primitive Value

[see JS: Primitive Value]

String Methods

JS: String.prototype

String is Immutable

JavaScript string is immutable. That means, any time you join string or get a substring or replace parts of the string, a new string is created.

All JavaScript string methods return a new string.

In practice, this means, if you need to create a long string, such as repeatedly append to a string one thousand times, you should not use a loop with append to do that. Because, the process of creating a long string is expensive.

String is 16 Bits Unit Sequence

Technically, each character in string is a 16 bits unit, not a character.

This is important when your string contains Unicode character such as emoji 😸.

[see JS: String Code Unit vs Code Point]

String Escape Sequence

Backslash sequence such as \n is called escape sequence.

[see JS: String Escape Sequence]

Unicode Escape Sequence

JS: Unicode Escape Sequence

String Topic

  1. JS: String Overview
  2. JS: Template String
  3. JS: String Object
  4. JS: String.prototype
  5. JS: String Code Unit vs Code Point
  6. JS: String Escape Sequence
  7. JS: Unicode Escape Sequence
  8. JS: Source Code Encoding
  9. JS: Allowed Characters in Identifier
  10. JS: Convert String to Number
  11. JS: Encode URL, Escape String
  12. JS: Format Number
  13. JS: JSON
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon