Searching Strings

Updated · 6 min read
easyES2026javascriptstringssearchlocalecompare

Searching a string means finding out whether, where and how often some text appears inside it. JavaScript gives you yes-or-no methods (includes, startsWith, endsWith), position methods (indexOf, lastIndexOf, search), and pattern methods (match, matchAll) that return the matching text. A separate method, localeCompare, compares strings the way people expect when sorting names.

In One Minute

  • Yes or no: includes(text), startsWith(text), endsWith(text). Case-sensitive.
  • Where: indexOf(text) gives the first position or -1; lastIndexOf searches from the end.
  • Patterns: search(regex) gives a position; match(regex) and matchAll(regex) give the matches.
  • Case-insensitive search: lowercase both sides first, or use a regular expression with the i flag.
  • Sorting text: a.localeCompare(b) orders strings alphabetically the human way.

Method Table

MethodDescription
includes(text, from)It is used to check whether the string contains text. Returns true or false.
startsWith(text, at)It is used to check whether the string begins with text.
endsWith(text, length)It is used to check whether the string ends with text.
indexOf(text, from)It is used to find the first position of text, or -1.
lastIndexOf(text, from)It is used to find the last position of text, or -1.
search(regex)It is used to find the position of the first regular expression match, or -1.
match(regex)It is used to get the first match with its groups, or all matches with the g flag.
matchAll(regex)It is used to loop over every match with its groups (the regex needs g).
localeCompare(other, locale, options)It is used to compare two strings for sorting; returns a negative number, 0 or a positive number.

Yes or No Searches

includes.js▶ Try it
const email = "srihitha.anamaneni@example.com";
 
console.log(email.includes("@"));
console.log(email.startsWith("srihitha"));
console.log(email.endsWith(".com"));
console.log(email.endsWith(".org"));
console.log(email.includes("Srihitha"));
Output
true
true
true
false
false

Explanation: the last line is false because searches are case-sensitive: "Srihitha" with a capital S doesn't appear. For a case-insensitive check, lowercase both sides:

ignore-case.js▶ Try it
const email = "srihitha.anamaneni@example.com";
const query = "Srihitha";
console.log(email.toLowerCase().includes(query.toLowerCase()));
Output
true

Finding Positions

indexOf returns the index of the first match, or -1 when there is none. The optional second argument says where to start searching:

index-of.js▶ Try it
const note = "late fee, late notice";
 
console.log(note.indexOf("late"));
console.log(note.indexOf("late", 1));
console.log(note.lastIndexOf("late"));
console.log(note.indexOf("paid"));
 
const at = "navika@example.com".indexOf("@");
console.log("navika@example.com".slice(at + 1));
Output
0
10
10
-1
example.com

Combining indexOf with slice is a common way to cut a string at a known character, such as taking the domain from an email address.

Counting Matches

To count how many times a substring appears, keep searching from just after the last match:

count.js▶ Try it
function countOccurrences(text, word) {
  let count = 0;
  let position = text.indexOf(word);
  while (position !== -1) {
    count++;
    position = text.indexOf(word, position + word.length);
  }
  return count;
}
 
console.log(countOccurrences("late fee, late notice, late again", "late"));
Output
3

Pattern Searches: search, match and matchAll

These methods take a regular expression, a pattern that describes text (covered fully in its own chapter). A few patterns are enough to see how they work: \d+ means "one or more digits", and the g flag means "find all matches".

match.js▶ Try it
const line = "Paid $120 on 01/05 and $85 on 02/05";
 
console.log(line.search(/\d/));
console.log(line.match(/\$\d+/)[0]);
console.log(line.match(/\$\d+/g));
 
for (const m of line.matchAll(/\$(\d+) on (\d\d\/\d\d)/g)) {
  console.log(`amount ${m[1]}, date ${m[2]}, at index ${m.index}`);
}
Output
6
$120
['$120', '$85']
amount 120, date 01/05, at index 5
amount 85, date 02/05, at index 23

Explanation:

  • search gives the index of the first digit.
  • match without g returns details about the first match; [0] is the matched text.
  • match with g returns an array of every matched text (or null if there is none).
  • matchAll gives each match with its capture groups (the parts in parentheses) and position, which match with g doesn't.

Comparing for Sorting: localeCompare

Comparing strings with < and > uses character codes, which puts every uppercase letter before every lowercase one and handles accents poorly. localeCompare compares the way a dictionary does. It returns a negative number if the first string comes first, 0 if they are equal, and a positive number otherwise, which is exactly what sort expects:

locale-compare.js▶ Try it
const names = ["advitha", "Srihitha", "Navika", "Émile", "zoe"];
 
console.log([...names].sort());
console.log([...names].sort((a, b) => a.localeCompare(b, "en-US")));
 
console.log("a".localeCompare("B", "en-US"));
console.log("resume".localeCompare("résumé", "en-US", { sensitivity: "base" }));
Output
['Navika', 'Srihitha', 'advitha', 'zoe', 'Émile']
['advitha', 'Émile', 'Navika', 'Srihitha', 'zoe']
-1
0

Explanation: the default sort orders by UTF-16 code units: uppercase letters first, then lowercase, then accented letters at the end. localeCompare sorts the way people expect. With sensitivity: "base", letters that differ only in accents or case compare as equal, which is useful for search.

For sorting many strings, new Intl.Collator("en-US").compare does the same job faster, because the collator is created once.

In Practice

The Fee Tracker's search box filters students as the user types. It matches anywhere in the name, ignores case and accents, and shows the results in dictionary order:

search-box.js▶ Try it
const students = ["Srihitha Anamaneni", "Navika Anamaneni", "Advitha Anamaneni", "Zoë Park"];
const collator = new Intl.Collator("en-US", { sensitivity: "base" });
 
function normalize(text) {
  return text.normalize("NFD").replace(/\p{Diacritic}/gu, "").toLowerCase();
}
 
function searchStudents(query) {
  const q = normalize(query.trim());
  return students
    .filter((name) => normalize(name).includes(q))
    .sort(collator.compare);
}
 
console.log(searchStudents("ANA"));
console.log(searchStudents("zoe"));
console.log(searchStudents("x"));
Output
['Advitha Anamaneni', 'Navika Anamaneni', 'Srihitha Anamaneni']
['Zoë Park']
[]

Explanation: normalize("NFD") splits accented letters into a base letter plus a separate accent mark, and the regular expression removes the marks, so "Zoë" becomes "zoe" for matching. The displayed names keep their accents.

Common Mistakes

if (str.indexOf(x)). False when the match is at index 0, true when it is -1. Use includes.

Forgetting searches are case-sensitive. Lowercase both sides, or use a regex with the i flag.

Calling .length on a match result without checking for null. Use ?? [].

Sorting names with the default sort. Capitals come first and accents go last. Use localeCompare or Intl.Collator.

Practice

Challenge: Write domainOf(email) that returns the part after @ in lowercase, or null if there is no @ or more than one.

Show solution
domain.js▶ Try it
function domainOf(email) {
  const at = email.indexOf("@");
  if (at === -1 || at !== email.lastIndexOf("@")) return null;
  return email.slice(at + 1).toLowerCase();
}
 
console.log(domainOf("Navika@Example.COM"));
console.log(domainOf("no-at-sign"));
console.log(domainOf("a@b@c.com"));
Output
example.com
null
null

Quick check: Searching strings

3 questions
1What does "Dallas".includes("dal") return?
2What does "fee".indexOf("x") return?
3Which is the right compare function to sort names alphabetically for people?

Key Takeaways

QuestionMethod
Does it contain X?str.includes(x)
Where is X?str.indexOf(x)
All matches of a patternstr.match(/p/g) ?? []
Matches with groupsfor (const m of str.matchAll(/p/g))
Sort ordera.localeCompare(b)

Was this tutorial helpful?

Lesson 22 of 139