JavaScript startsWith(): Check if a String Starts With Text

Deepak Prasad
Short on time?Beta Get the gist of this 2-minute read in seconds, then ask follow-up questions

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

javascript
console.log("starts-basic:", "JavaScript".startsWith("Java"));
Output

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

javascript
console.log("starts-position:", "Hello JavaScript".startsWith("Java", 6));
Output

You should see one line logging starts-position: true.

The second argument tells JavaScript where to start checking.


Method 3: Remember Case Sensitivity

javascript
console.log("JavaScript".startsWith("java"));
Output

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

javascript
const text = "JavaScript";
console.log(text.toLowerCase().startsWith("java"));
Output

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.


Official Documentation

Finished reading?Beta Get the key takeaways in seconds, then ask follow-up questions
Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains.

  • JavaScript
  • Web Design