Learn JavaScript
❯ strings_regex.string_search

Searching: includes, indexOf & startsWith in JavaScript

$concept

Three search tiers: includes (boolean presence — the modern default), indexOf/lastIndexOf (positions, -1 when absent), and startsWith/endsWith (boundary checks). includes reads as intent (if (url.includes("https"))), indexOf serves slicing and pre-regex code, and the boundary pair validates prefixes/suffixes directly.

Case sensitivity trips everyone once — normalize both sides (toLowerCase) before comparing, or reach for regex with the i flag. For presence questions, includes beats indexOf !== -1 on readability every time.

$how it works
1

includes for presence

"hello".includes("ell") is true — boolean answers without index bookkeeping.

2

indexOf for positions

Returns the first index or -1 — compare !== -1 explicitly, since index 0 is falsy.

3

Boundaries directly

startsWith("https") and endsWith(".png") check edges — URL and file validation staples.

4

Normalize case first

Lowercase both sides before comparing, or use case-insensitive regex — raw mixed-case search misses.

$example
let url = "https://example.com/a.png";
console.log(url.includes("https"));
console.log(url.indexOf("z"));
console.log(url.endsWith(".png"));
Output
true
-1
true
1includes finds the https substring — true.
2indexOf finds no z — the -1 sentinel for absence.
3endsWith confirms the .png suffix directly.
$use cases
Presence checks with includes instead of indexOf comparisons
URL and file-type validation via startsWith/endsWith
Finding positions for subsequent slicing
Case-normalized search before comparing user text

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.