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]
orArray.from(str)
to iterate code points.
Checks for Understanding
- Are strings mutable or immutable in JavaScript?
- When would
replaceAll
be preferable toreplace
?
Show answers
- Strings are immutable; operations return new strings.
- When you need to replace all occurrences of a substring without using a global RegExp.
Exercises
- Write a function that capitalizes the first letter of a string (e.g., "hello" → "Hello").
- Count how many times the letter
l
appears in"hello world"
using a loop orsplit
.