Typorithm · medium

replace & match

string-replacecollectionsreplaceregexmatch
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn replace & match

0%

String Methods

replace with a string argument swaps only the first occurrence; replaceAll swaps every one. A regex with the g flag makes replace global, and match with a global regex returns an array of all matches.

replace(needle, value) with a plain string replaces only the first match — "banana".replace("a", "o") gives "bonana". That first-only behavior is a classic gotcha.

To swap every occurrence, use replaceAll, or pass a regex with the global g flag: "banana".replace(/a/g, "o"). Regex unlocks pattern matching like /\d+/g for runs of digits.

match(regex) returns the matched text: with a global regex it returns an array of all matches, so "id 42 and 7".match(/\d+/g) yields ["42", "7"].

01

replace with a string swaps only the first match.

02

replaceAll or a /g regex swaps every match.

03

match with /g returns an array of all matches.

const a = "banana".replace("a", "o")
const b = "banana".replaceAll("a", "o")
const c = "id 42 and 7".replace(/\d+/g, "#")
const nums = "id 42 and 7".match(/\d+/g)

Read the implementation

Connect each part of the code to the concept before you type.

1. Replace first only

With a string argument, replace swaps only the first match, giving "bonana".

"banana".replace("a", "o")

2. Replace every match

replaceAll swaps every occurrence of the substring, giving "bonono".

"banana".replaceAll("a", "o")

3. Global regex

A regex with the g flag matches every run of digits, so replace touches them all.

/\d+/g

4. match collects hits

match with a global regex returns an array of every match: ["42", "7"].

"id 42 and 7".match(/\d+/g)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

replace & match: Lesson & Practice · Typorithm | ApplyDjinn