JavaScript String Search
Very often you need to know whether a string contains some text, where it occurs, or whether it starts or ends a certain way. JavaScript has a small family of methods for that, plus regular-expression–based search for more complex patterns.
includes, startsWith, endsWith
These answer yes/no questions and return a boolean — the most readable choice when you don't need a position:
const file = "holiday-photo.JPG";
console.log(file.includes("photo"));
console.log(file.startsWith("holiday"));
console.log(file.endsWith(".jpg")); // case-sensitive!
console.log(file.toLowerCase().endsWith(".jpg"));
console.log(file.startsWith("photo", 8)); // start checking at index 8true
true
false
true
true
Tip: All string search is case-sensitive. Normalise with
toLowerCase()first when case shouldn't matter.
indexOf and lastIndexOf
indexOf returns the position of the first occurrence, or -1 if the text isn't found. lastIndexOf searches from the end:
const sentence = "the cat sat on the mat";
console.log(sentence.indexOf("at"));
console.log(sentence.lastIndexOf("at"));
console.log(sentence.indexOf("the", 1)); // start searching at index 1
console.log(sentence.indexOf("dog"));
if (sentence.indexOf("dog") === -1) {
console.log("no dog here");
}5
20
15
-1
no dog here
A common pattern is combining indexOf with slice to cut a string at a separator:
const header = "Content-Type: text/html";
const colon = header.indexOf(":");
const name = header.slice(0, colon);
const value = header.slice(colon + 1).trim();
console.log(name, "=>", value);Content-Type => text/html
Counting all occurrences
indexOf can keep searching from just after the previous match:
const dna = "AGCTTAGCTAAGC";
let count = 0;
let pos = dna.indexOf("AGC");
while (pos !== -1) {
count++;
console.log("found at", pos);
pos = dna.indexOf("AGC", pos + 1);
}
console.log("total:", count);found at 0
found at 5
found at 10
total: 3
Searching with regular expressions
For patterns rather than fixed text — "any digits", "a word starting with a capital" — use a regular expression:
| Method | Returns |
|---|---|
str.search(regex) |
index of the first match, or -1 |
str.match(regex) |
first match details, or all matches with the g flag, or null |
str.matchAll(regex) |
iterator of every match with details (needs g) |
regex.test(str) |
true / false |
const note = "Order 1042 shipped on day 7, invoice 88.";
console.log(note.search(/\d/)); // first digit
console.log(note.match(/\d+/g)); // all numbers
console.log(/invoice/i.test(note));
for (const m of note.matchAll(/(\w+) (\d+)/g)) {
console.log(`${m[1]} -> ${m[2]} (at ${m.index})`);
}6
[ '1042', '7', '88' ]
true
Order -> 1042 (at 0)
day -> 7 (at 22)
invoice -> 88 (at 29)
Regular expressions are a language of their own; for now, remember that \d means "a digit", \w "a word character", + "one or more", and the g and i flags mean "global" and "ignore case".
Which method should I use?
| Question | Method |
|---|---|
| Does it contain X? | includes |
| Does it start / end with X? | startsWith / endsWith |
| Where is X? | indexOf / lastIndexOf |
| Does it match a pattern? | regex.test(str) |
| What are all the matches? | match with g, or matchAll |
Test yourself
What does "banana".indexOf("x") return?
- 0
- null
- -1
- undefined
What does "Report.PDF".endsWith(".pdf") return?
- true
- false
- -1
- ".pdf"
What does "a1b22c333".match(/\d+/g) return?
- ["1"]
- ["1", "22", "333"]
- ["1", "2", "2", "3", "3", "3"]
- 6