startsWith() checks whether a JavaScript string begins with a specific substring. It returns true or false and is case-sensitive.
Use it for prefix checks such as URL paths, file names, command strings, IDs, and user input validation.
In Node.js path validation, combine it with path.relative() as shown in
the subdirectory containment example
instead of comparing raw path prefixes.
Environment: Node.js v20.18.2. After each runnable snippet, the following paragraph states the expected console output (order and values).
Method 1: Check the Start of a String
console.log("starts-basic:", "JavaScript".startsWith("Java"));You should see one line logging starts-basic: true.
The string begins with Java, so the result is true.
Method 2: Use the Position Argument
console.log("starts-position:", "Hello JavaScript".startsWith("Java", 6));You should see one line logging starts-position: true.
The second argument tells JavaScript where to start checking.
Method 3: Remember Case Sensitivity
console.log("JavaScript".startsWith("java"));You should see one line logging false.
Convert both strings to the same case when you need a case-insensitive check.
Method 4: Case-Insensitive startsWith
const text = "JavaScript";
console.log(text.toLowerCase().startsWith("java"));You should see one line logging true.
This is useful for user-entered text.
Common Questions About startsWith in JavaScript
Is startsWith case-sensitive?
Yes. "JavaScript".startsWith("java") returns false.
What does startsWith return?
It returns a boolean: true if the string starts with the search text, otherwise false.
Can startsWith start checking from another position?
Yes. Pass the position as the second argument: str.startsWith(search, position).
Summary
Use startsWith() to check whether a JavaScript string begins with a specific substring. It is case-sensitive, supports an optional position argument, and returns a boolean, making it useful for validation, routing, prefixes, and file-name checks.
