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

Learn JavaScript startsWith() with examples for checking string prefixes, using the position argument, case sensitivity, and alternatives.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

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

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.

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

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 …