1. Replace first only
With a string argument, replace swaps only the first match, giving "bonana".
"banana".replace("a", "o")Typorithm · medium
Step 1 of 8 · intro card
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"].
replace with a string swaps only the first match.
replaceAll or a /g regex swaps every match.
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)Connect each part of the code to the concept before you type.
With a string argument, replace swaps only the first match, giving "bonana".
"banana".replace("a", "o")replaceAll swaps every occurrence of the substring, giving "bonono".
"banana".replaceAll("a", "o")A regex with the g flag matches every run of digits, so replace touches them all.
/\d+/gmatch with a global regex returns an array of every match: ["42", "7"].
"id 42 and 7".match(/\d+/g)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.