Position Parameters in Search Methods
You'll learn how to tell JavaScript's search methods where to begin looking in a string, giving you fine-grained control over your searches.
The Core Idea
Many string search methods accept an optional second parameter that specifies where the search should start. Instead of always searching from the beginning (or end), you can say "start looking from character 10" or "begin at position 5."
Think of it like telling someone: "Search this bookshelf for a red book, but start from the third shelf instead of the top." You're narrowing where the search begins.
Methods That Accept Position Parameters
indexOf(searchString, position)
The position parameter tells indexOf() where to start searching forward:
let text = "hello world hello";
text.indexOf("hello"); // 0 (finds first occurrence)
text.indexOf("hello", 1); // 12 (starts searching from index 1, skips first match)
text.indexOf("hello", 13); // -1 (starts too late, no match found)
includes(searchString, position)
The position parameter sets where includes() begins checking:
let message = "JavaScript is awesome";
message.includes("Java"); // true (searches from start)
message.includes("Java", 5); // false (starts at index 5, misses "Java")
message.includes("is", 10); // true (finds "is" at position 11)
lastIndexOf(searchString, position)
Here, position sets where to start searching backward:
let phrase = "test test test";
phrase.lastIndexOf("test"); // 10 (searches backward from end)
phrase.lastIndexOf("test", 8); // 5 (searches backward from index 8)
Why This Matters
Position parameters let you search specific portions of strings, skip known matches, or implement "find next occurrence" logic without slicing strings.
Key Takeaway: Position parameters in search methods control the starting point of your search, allowing you to target specific regions of a string efficiently.