Searching and replacing strings in JavaScript is really four different questions that wear the same coat. Is this text present, where does it start, what exactly matched, and what should the text become. includes, indexOf, search, match, and replace each answer one of those questions, and the small differences between them, such as case sensitivity, first-match-only, and the global flag, account for most of the string bugs that you will meet. The previous lesson in this module showed you how to split a line into pieces and how to join them back together, and searching is the natural next step, because a search is really a way of finding one piece inside a bigger piece. The last lesson in the module takes everything you have learned and applies it to the text that real people type.
The previous lesson in this module covered "Splitting, Joining and Parsing Text", and the next lesson in this module is about "Cleaning User Input: Trim, Case and Validation Basics".
Which search tool should you use: includes, indexOf or search?
Start with the question that you are really asking. If the answer is yes or no, use includes. If you need to know where the text sits, use indexOf for a plain string or search for a pattern. Both of those hand back the index of the first match, or -1 when there is nothing to find, so you can compare the result against -1 instead of hunting for undefined.
const note = 'Order #A-1024 failed for card 4111 1111 1111 1111';
console.log(note.includes('card')); // true
console.log(note.indexOf('card')); // 25
console.log(note.lastIndexOf('1111')); // 45
console.log(note.search(/A-\d+/)); // 7
console.log(note.search(/CARD/)); // -1
console.log(note.search(/card/i)); // 25
console.log(note.indexOf('CARD')); // -1
Two things in that output are worth reading twice. indexOf and includes take a plain string, so they are always case sensitive, which is why note.indexOf('CARD') is -1 when the log line contains a small letter c. search takes a regular expression, and a regular expression can carry flags. The i flag makes matching ignore the case, which is why note.search(/card/i) lands on the same position as note.indexOf('card'). If you want case-insensitive matching with a plain string, lower-case both sides yourself with note.toLowerCase().includes('card').
| Method | Argument | Gives back | Reach for it when |
|---|---|---|---|
includes | plain string | true or false | you only need a yes or no answer |
indexOf | plain string | first index, or -1 | you need the position of a known substring |
lastIndexOf | plain string | last index, or -1 | the text may repeat and you want the final one |
search | regular expression | first index, or -1 | the shape of the text matters more than its exact wording |
There is one asymmetry that is worth remembering. includes and indexOf look for a literal substring, so a dot or an asterisk in the text you are looking for is matched literally, while search treats its argument as a pattern. When the text comes from a user, a single typed dot will otherwise match any character at all.
Why did replace only change the first occurrence?
Because replace replaces the first match and then stops. That is deliberate, because the method was designed for fixing one thing inside a larger string, but it is the single most common surprise in string handling. replace looks like it should behave like a find-and-replace-all tool, and it does not.
const log = 'user [email protected] token=abc123 user [email protected]';
console.log(log.replace('user', 'account'));
console.log(log.replace(/user/g, 'account'));
console.log(log.replaceAll('user', 'account'));
try {
'banana'.replaceAll(/a/, 'x');
} catch (err) {
console.log(err.constructor.name + ': ' + err.message);
}
Read the first three lines together. A plain string needle replaces only the first occurrence. A regular expression needle also replaces only the first match, unless you add the g flag, which means "global" and asks the engine to keep going. replaceAll is the method whose whole job is replacing everything, so it does not need the flag when you give it a string. If you hand it a regular expression instead, that expression has to be global, otherwise the engine refuses the call with a TypeError rather than guessing. The error message names the problem exactly, so if you see it, the fix is to add g to the pattern and not to reach for a loop.
One more detail shapes how you write the replacement text. The replacement is not a literal. It is a template, and a $ followed by a character means something specific, which is occasionally useful and occasionally a trap.
How do capture groups and dollar signs change the replacement text?
Parentheses inside the pattern create capture groups, and the replacement text can refer to them by number. $1 is the first group, $2 is the second, and so on. $& inserts the whole text that matched, and $$ inserts a literal dollar sign, which is useful when the text you are writing contains money.
const line = '2026-03-04 ERROR payment timeout';
console.log(line.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3/$2/$1'));
console.log('order #42'.replace(/#\d+/, '[$&]'));
console.log('cost: 10 USD'.replace('USD', '$$'));
The first line swaps a date from year-first to day-first by rearranging the captured pieces, and there is no need to split the string apart and stitch it back together by hand. The second line wraps the matched text in brackets by using $&. The third one is the one to watch, because replace('USD', '$$') does not produce two dollar signs. $$ is an escape for a single literal $, so the output is cost: 10 $.
When the replacement depends on the match itself, pass a function instead of a string. The function receives the matched text and any capture groups, and it returns the text to insert.
How do I get every match, with the parts I need?
match is the shortcut for "give me all the matches". With a global regular expression it returns an array of the matched strings, or null when nothing matched at all. Without the global flag it returns the first match, but as an array that also carries your capture groups.
const text = '[email protected], [email protected]';
console.log(text.match(/[\w.+-]+@[\w-]+\.[\w.]+/g));
for (const match of text.matchAll(/(?<user>\w+)@(?<host>[\w.]+)/g)) {
console.log(match.groups.user, '->', match.groups.host);
}
The first line hands back both addresses as plain strings, which is all that you need for a list of links. The loop uses matchAll, which requires a global regular expression and gives you an iterator of match objects. Each match object exposes the full text at match[0], the capture groups by position, and, when you name the groups inside the pattern, the named groups through match.groups. Naming the groups is worth the extra characters, because (?<user>\w+) tells you what the text is at the point where you read it six months later.
Why does my regex alternate between true and false?
This one has burned a lot of beginners. A regular expression object with the g flag remembers where it stopped, in a property called lastIndex. When you call test on it, the engine starts looking from that remembered position instead of from the beginning of the string. A match that fails resets the position, so the next call succeeds again, and that gives you an alternating true, false, true, false pattern that looks like the regular expression itself is broken.
const global = /\d/g;
console.log(global.test('a1')); // true
console.log(global.test('a1')); // false
console.log(global.lastIndex); // 0
console.log(global.test('a1')); // true
The fix is one of three things. Create the pattern inside the function that uses it, so that every call gets a fresh object. Reset lastIndex to zero before each test. Or drop the g flag when you only need a yes or no answer, because a pattern without g keeps no state at all. The same trap explains why a validation helper mysteriously passes every other field on a form.
The related trap is building a pattern out of raw user text. Characters like ., *, +, ?, and the brackets have a special meaning inside a regular expression, so a user who searches for a.b will match axb as well. Escape them before you build the pattern.
function escapeRegExp(text) {
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
const pattern = new RegExp(escapeRegExp('a.b*c'));
console.log(pattern.test('xxa.b*cxx')); // true
console.log(pattern.test('xxaxbxcxx')); // false
Four questions to ask before you search
- Do I need a position or just a yes or no? Use
includesfor yes or no, andindexOforsearchfor a position. - Is the text literal or is it a shape? Use the plain-string methods for literal text, and a regular expression when the shape matters.
- One occurrence or every occurrence? Use
replacefor the first one, andreplaceAllor a pattern with thegflag for all of them. - Where did the text come from? If it came from a user, escape it before you turn it into a pattern.
One habit prevents most of this class of bug. Pick the method by the question that you need answered, write down the output that you expect, and then compare it with what you actually got. String handling fails quietly, and a single console.log is usually cheaper than an hour of guessing.
Try it yourself: write a file called redact.js that takes a log line and hides sensitive data in it. Start with this input: '2026-03-04 ERROR login for [email protected] from 10.0.0.7 token=abc123'. Use replace with a capture group to turn the email into ada@***.com and the token into token=***, then repeat the whole thing with replaceAll on a line that contains two emails and confirm that both of them are hidden. Add one more step: use matchAll to pull every email address out of a paragraph of three sentences and print them as a list, and use escapeRegExp so that searching for the literal text [email protected] does not also match userXexample.com.