What You'll Learn
You'll learn how to quickly check if a string begins or ends with specific characters or substrings using JavaScript's built-in startsWith() and endsWith() methods.
The Core Idea
Think of these methods as specialized inspectors that only look at the beginning or end of a string. Instead of searching the entire string (like includes() does), they focus on exactly where you tell them to look — perfect when you need to verify prefixes or suffixes.
startsWith(searchString) returns true if the string begins with the search string, false otherwise.
endsWith(searchString) returns true if the string ends with the search string, false otherwise.
How They Work
const filename = "report.pdf";
filename.startsWith("report"); // true
filename.startsWith("data"); // false
filename.endsWith(".pdf"); // true
filename.endsWith(".doc"); // false
Both methods are case-sensitive:
const message = "Hello World";
message.startsWith("hello"); // false (lowercase h)
message.startsWith("Hello"); // true
You can also specify a position to start searching from (for startsWith()) or to treat as the end (for endsWith()):
const text = "JavaScript is fun";
text.startsWith("Script", 4); // true (starts at index 4)
text.endsWith("Java", 4); // true (checks up to index 4)
Real-World Use Cases
These methods shine when validating file extensions, URL protocols, or command prefixes:
const url = "https://example.com";
url.startsWith("https://"); // true - secure connection
const file = "image.png";
file.endsWith(".png"); // true - it's a PNG file
Key Takeaway: Use startsWith() and endsWith() when you need to check the beginning or end of a string — they're more efficient and clearer than using includes() or manual character checking.