JavaScript String startsWith() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Instance method

What You’ll Learn

String.prototype.startsWith() is a case-sensitive prefix check that returns true or false (same API as MDN String.prototype.startsWith()). Learn the optional position, empty-string behavior, why regex is not allowed, how it compares to endsWith() and includes(), five examples, and try-it labs.

01

Kind

Instance method

02

Returns

true / false

03

Case

Sensitive

04

Regex?

No (TypeError)

05

Mutates?

No

06

Baseline

Widely available

Introduction

Need to know whether a string begins with a certain prefix — a protocol, a filename stem, or a command keyword? startsWith() answers with a clear boolean.

The check is always case-sensitive. An optional position lets you treat a later index as the new “start.” Regular expressions are not allowed — pass a string (or a value that coerces to a string).

💡
Beginner tip

Prefer str.startsWith("https://") over str.indexOf("https://") === 0 — it reads exactly what you mean.

This page is part of JavaScript String Methods. Related topics include includes() and indexOf().

Understanding the startsWith() Method

str.startsWith(searchString, position) checks whether searchString appears at the beginning of the string (or at position if you provide one).

  • Returns a boolean — ideal for if checks.
  • Case-sensitive; empty searchString always matches.
  • Throws TypeError if searchString is a regex.
  • Does not change the original string.

📝 Syntax

General form of String.prototype.startsWith:

JavaScript
str.startsWith(searchString)
str.startsWith(searchString, position)

Parameters

  • searchString — the prefix to look for. Cannot be a regex. Other values are coerced to strings (omitting it searches for "undefined" — rarely useful).
  • position (optional) — index where the prefix is expected to start. Defaults to 0.

Return value

true if the characters are found at the start (including when searchString is ""); otherwise false.

Exceptions

TypeError if searchString is a regular expression.

Common patterns

JavaScript
"Hello".startsWith("He");      // true
"Hello".startsWith("he");      // false (case-sensitive)
"Hello".startsWith("llo", 2);  // true
"Hello".startsWith("");        // true
"https://x.com".startsWith("https://"); // true

⚡ Quick Reference

GoalCode
Check a prefixstr.startsWith(prefix)
Check from an indexstr.startsWith(prefix, i)
Ignore casestr.toLowerCase().startsWith(p.toLowerCase())
Check a suffixstr.endsWith(suffix)
Find anywherestr.includes(part)

🔍 At a Glance

Four facts to remember about String.startsWith().

Returns
boolean

true or false

Case
sensitive

Exact match

Regex
TypeError

Strings only

Mutates
no

Read-only check

📋 startsWith() vs endsWith() vs includes()

startsWith()endsWith()includes()
Looks atBeginning (or from position)End (or up to length)Anywhere
Returnsbooleanbooleanboolean
Regex allowed?NoNoNo
Best forPrefixes / protocolsFile extensionsSubstring presence

Examples Gallery

Examples follow MDN String.startsWith() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

Simple prefixes and the optional start position.

Example 1 — Basic startsWith()

MDN demo: check a weekend plan string.

JavaScript
const str = "Saturday night plans";

str.startsWith("Sat");
// true

str.startsWith("Sat", 3);
// false
Try It Yourself

How It Works

Without a position, the check starts at index 0. With position = 3, the string is treated as starting at "urday...", so "Sat" no longer matches.

Example 2 — Prefix from a Position

MDN demo: Hamlet line — find a phrase that is not at index 0.

JavaScript
const str = "To be, or not to be, that is the question.";

str.startsWith("To be");      // true
str.startsWith("not to be");  // false
str.startsWith("not to be", 10); // true
Try It Yourself

How It Works

Index 10 is where "not to be" begins in the sentence. position does not search forward — it sets where the prefix must sit.

📈 Practical Patterns

Case rules, regex errors, and real-world prefixes.

Example 3 — Case Sensitivity and Empty Prefix

Exact matches only — and the empty-string quirk.

JavaScript
"File.PDF".startsWith("file");  // false
"File.PDF".toLowerCase().startsWith("file"); // true

"Hello".startsWith("");  // true
"".startsWith("");       // true
Try It Yourself

How It Works

Lower-case both sides for a case-insensitive prefix check. An empty search string always returns true.

Example 4 — Regex Is Not Allowed

Like includes() and endsWith(), regex arguments throw.

JavaScript
try {
  "hello".startsWith(/he/);
} catch (err) {
  console.log(err.name); // TypeError
}

// Pattern check instead:
/^he/i.test("Hello"); // true
Try It Yourself

How It Works

Use a string with startsWith, or switch to RegExp.prototype.test / String.prototype.search for patterns.

Example 5 — URLs, Paths, and Commands

Everyday prefix helpers.

JavaScript
function isSecureUrl(url) {
  return url.startsWith("https://");
}

function isJsFile(path) {
  const name = path.split("/").pop();
  return name.startsWith("index") || name.endsWith(".js");
}

isSecureUrl("https://codetofun.com"); // true
isSecureUrl("http://example.com");    // false
"npm run build".startsWith("npm ");   // true
Try It Yourself

How It Works

Prefix checks keep validation readable. Pair with endsWith when you care about the other end of the string.

🚀 Common Use Cases

  • URL / protocol checksstartsWith("https://").
  • Command routing — detect prefixes like "/help" or "npm ".
  • Path filters — keep files under a folder prefix.
  • Feature flags / tags — strings that begin with a known marker.
  • Not for “contains” — use includes() when the text can appear anywhere.
  • Not for regex prefixes — use /^pattern/ with test().

🧠 How startsWith() Decides

1

Read searchString / position

Default position to 0; reject regex with TypeError.

Input
2

Compare the prefix

Check characters from position for an exact match.

Compare
3

Handle empty search

Empty searchString counts as a successful match.

Edge
4

Return true or false

Original string is never modified.

📝 Notes

  • The search is case-sensitive.
  • position sets where the prefix must start — it does not scan forward.
  • Empty searchString always returns true.
  • Passing a regex throws TypeError.
  • Omitting searchString searches for the literal "undefined".
  • Pair with endsWith() for suffix checks and includes() for “anywhere.”

Browser & Runtime Support

String.prototype.startsWith() is Baseline Widely available — supported across modern browsers since September 2015.

Baseline · Widely available

String.startsWith()

Safe for production in browsers and runtimes (Node.js, Deno, Bun). Prefer startsWith() for readable prefix checks.

Universal Widely available
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
startsWith() Excellent

Bottom line: Use String.startsWith() to test prefixes. Remember it is case-sensitive, and regex arguments throw TypeError.

Conclusion

String.prototype.startsWith() is the clearest way to ask “does this string begin with …?” — with an optional position for mid-string prefixes. Keep it for literal strings; reach for regex APIs when you need patterns.

Continue with includes(), match(), or the String methods hub.

💡 Best Practices

✅ Do

  • Use startsWith for readable prefix checks
  • Normalize case when matching user input
  • Pass an explicit string — avoid accidental undefined
  • Combine with endsWith for file-type logic
  • Use position when the “start” is mid-string

❌ Don’t

  • Pass a regex to startsWith
  • Assume case-insensitive matching
  • Use indexOf(...) === 0 when startsWith is clearer
  • Expect position to search later occurrences
  • Forget empty search strings always match

Key Takeaways

Knowledge Unlocked

Five things to remember about String.startsWith()

Boolean prefix check — case-sensitive, no regex.

5
Core concepts
🔍 02

Checks

prefix

Role
🔢 03

Case

sensitive

Rule
04

Regex

TypeError

Limit
05

Mutates

no

Immutable

❓ Frequently Asked Questions

String.prototype.startsWith(searchString, position?) returns true if the string begins with searchString (optionally checked from position), otherwise false. The search is case-sensitive.
Yes. "Hello".startsWith("hello") is false. Normalize both sides with toLowerCase() when you need a case-insensitive prefix check.
No. If searchString is a RegExp, startsWith() throws TypeError. Use RegExp.test() or String.search() for pattern checks.
true for any string. An empty search string is treated as a match at the start.
position is the index where the prefix is expected to begin (default 0). For example "abcdef".startsWith("de", 3) is true because indexes 3–4 are "de".
startsWith() only checks the beginning (or from position as a new start). includes() looks for the substring anywhere in the remaining text.
Did you know?

startsWith, endsWith, and includes all reject regex arguments with TypeError — a deliberate design so boolean substring helpers stay simple. For patterns at the start of a string, use /^.../ with test().

More String Methods

Return to the hub for slice, trim, replace, and more.

String methods hub →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful