JavaScript - Strings

Overview

Estimated time: 30–40 minutes

Strings are immutable sequences of UTF-16 code units. Learn common operations, search/replace, and pitfalls with Unicode.

Learning Objectives

  • Create and manipulate strings (slice, substring, replace).
  • Search with indexOf/includes/startsWith/endsWith.
  • Understand immutability and common Unicode issues.

Prerequisites

Basics

const a = 'hello';
const b = "world";
const c = a + ' ' + b;    // 'hello world'
const len = c.length;     // 11

Access & slicing

c[0];            // 'h'
c.slice(0, 5);    // 'hello'
c.substring(6);   // 'world'

Search

c.includes('hello');       // true
c.startsWith('he');        // true
c.endsWith('world');       // true
c.indexOf('o');            // 4

Replace

'a-b-c'.replace('-', '_');      // 'a_b-c'
'a-b-c'.replaceAll('-', '_');   // 'a_b_c'

Unicode notes

  • Some characters use surrogate pairs (length may differ from visible glyph count).
  • Use [...str] or Array.from(str) to iterate code points.

Checks for Understanding

  1. Are strings mutable or immutable in JavaScript?
  2. When would replaceAll be preferable to replace?
Show answers
  1. Strings are immutable; operations return new strings.
  2. When you need to replace all occurrences of a substring without using a global RegExp.

Exercises

  1. Write a function that capitalizes the first letter of a string (e.g., "hello" → "Hello").
  2. Count how many times the letter l appears in "hello world" using a loop or split.