search() vs indexOf() in JavaScript
Intermediate · 4 min read
Sometimes you know exactly what you are looking for: the word 'Order', the text '42'. Other times you only know what kind of thing you want: the first digit, the first capital letter, the first space. indexOf handles the first case. search handles the second.
In this tutorial you will find the position of the first digit in 'Order 42 shipped on 2025-04-09'. Then you will compare search with indexOf and learn the two things search can do that indexOf can't, and the one thing it can't do that indexOf can. You should know that indexOf returns the position of a match, or -1 when there is none.
Patterns, in one minute
A regular expression, or regex, is a pattern that describes text. You write it between two slashes. Here are the only pieces this exercise needs:
/z/matches the letterz./[0-9]/matches any one digit. The square brackets mean "one character from this set", and0-9is the set of digits./[0-9]+/matches one or more digits in a row.+means "one or more of the thing before".- A letter after the closing slash is a flag that changes how the pattern works.
imeans "ignore case", so/order/imatchesOrdertoo.
search takes a pattern like this and returns the position of the first match, or -1, just like indexOf.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
10 search, and how it differs from indexOf
fairFind the position of the first digit in a line of text. Then work out the two things search can do that indexOf cannot, and the one thing it cannot do that indexOf can.
Stuck? Three hints, smallest first
- 1.
searchtakes a pattern, so it can find "a digit" rather than a known string. - 2. A string argument is converted to a regular expression, which makes
.a wildcard. - 3.
searchaccepts no start position at all, so skipping ahead means slicing first.
Step 1: find the first digit
const line = 'Order 42 shipped on 2025-04-09';
console.log(line.search(/[0-9]/)); // 6
console.log(line.indexOf('42')); // 6
search found the first digit without being told which digit. indexOf gets the same answer here only because we already knew the text was '42'. If the order number changed, the indexOf line would need changing too, and the search line wouldn't.
Step 2: no match is -1
const line = 'Order 42 shipped on 2025-04-09';
console.log(line.search(/z/)); // -1
Same "not found" signal as indexOf, so the same habit applies: compare with -1, because a match at position 0 counts as false in an if.
Step 3: ignore case with a flag
const line = 'Order 42 shipped on 2025-04-09';
console.log(line.search(/order/i)); // 0
console.log(line.toLowerCase().indexOf('order')); // 0
With search, ignoring case is one letter, the i flag. With indexOf, you have to lower-case the text yourself first. That is the second thing search can do that indexOf can't do on its own.
Step 4: a string becomes a pattern
You can pass search a plain string. But it doesn't search for that string. It turns it into a pattern first.
console.log('abc'.search('.')); // 0
console.log('abc'.indexOf('.')); // -1
In a pattern, a dot means "any character". So search('.') matches the a at position 0, even though there is no dot in 'abc'. indexOf treats the dot as a dot, finds none, and returns -1.
This matters when the text you search for comes from a user. Someone typing '1.5' into a search box would also match '105' with search. Use indexOf for plain text, or escape the special characters first.
Step 5: the g flag changes nothing
The g flag means "global", find every match. Some methods use it. search ignores it.
const line = 'Order 42 shipped on 2025-04-09';
console.log(line.search(/[0-9]+/g)); // 6
search always reports only the first match.
Step 6: what search can't do
indexOf takes a second number, the position to start from. search doesn't. Pass one and it is simply ignored:
const line = 'Order 42 shipped on 2025-04-09';
console.log(line.indexOf('2', 10)); // 20
console.log(line.search(/[0-9]/, 10)); // 6, the 10 is ignored
To search from position 10, cut the string first, search the piece, then add the 10 back:
const line = 'Order 42 shipped on 2025-04-09';
const piece = line.slice(10);
console.log(piece.search(/[0-9]/)); // 10
console.log(10 + piece.search(/[0-9]/)); // 20
The first answer is 10 because it is a position inside the piece, not inside the whole line. Forgetting to add the offset back is the usual mistake here. (This simple version would also need care when the piece has no digit, because 10 + -1 is 9, not -1.)
The full solution
Here is the complete answer: search against indexOf on the same line, the dot that turns into a wildcard, and the slice-and-add workaround. Press Run to see each result.
const line = 'Order 42 shipped on 2025-04-09';
console.log('search(/[0-9]/) :', line.search(/[0-9]/));
console.log('indexOf("42") :', line.indexOf('42'));
console.log("'abc'.search('.') :", 'abc'.search('.'), '<- a string is converted to a regex');
console.log("'abc'.indexOf('.'):", 'abc'.indexOf('.'), '<- a dot is just a dot here');
Output
10 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('search finds the first digit without knowing which digit', line.search(/[0-9]/), 6);
test('indexOf would have to be told the exact text', line.indexOf('42'), 6);
test('search returns -1 when nothing matches', line.search(/z/), -1);
test('a string argument becomes a regex, so a dot is a wildcard', 'abc'.search('.'), 0);
test('while indexOf treats the dot literally', 'abc'.indexOf('.'), -1);
test('search ignores the g flag and always reports the first match', line.search(/[0-9]+/g), 6);
test('case-insensitivity is a flag rather than a second method', line.search(/order/i), 0);
test('indexOf needs both sides lower-cased instead', line.toLowerCase().indexOf('order'), 0);
test('search takes NO start position, so a second argument is ignored', line.search(/[0-9]/, 10), 6);
test('skipping ahead means slicing first and adding the offset back', 10 + line.slice(10).search(/[0-9]/), 20);
search is indexOf for patterns, with one missing feature: no start position. The last assertion shows the workaround, and the + 10 is the part people forget — the index you get back is relative to the slice, not to the original string.
The string-becomes-a-regex conversion is worth pausing on. 'abc'.search('.') returns 0 because '.' is compiled into a pattern matching any character. If your needle came from user input, search is the wrong method unless you escape it first, which is exercise 30.
Common mistakes
- Passing user text straight to
search. Characters like.and+become pattern symbols. UseindexOforincludesfor plain text. - Passing a start position to
search. It is ignored. Slice first and add the offset back. - Testing the result with
if (pos). A match at 0 counts as false. Compare with-1.
Try it yourself
- Find the position of the first capital letter in
'hello World'with/[A-Z]/. - Find the position of the first space in
'Ada Lovelace'withsearch(/ /), then check it withindexOf(' '). - Write
searchFrom(text, pattern, start)that searches fromstartand still returns-1when there is no match.