Skip to content

String.prototype.startsWith(): check a prefix (ES2015)

  • What String.prototype.startsWith() returns and what its position argument does.
  • The edge cases: empty prefixes, clamping, coercion and the TypeError for a regular expression.
  • How to match path prefixes by whole segment, and several prefixes at once.
  • Why startsWith on a URL string is not a security check.

TL;DR: str.startsWith(searchString, position) returns true if the characters of str starting at position (default 0) are exactly searchString. It is case-sensitive and compares UTF-16 code units.

It was added in ECMAScript 2015 (ES6) and works in every current browser and server runtime (see Compatibility). Its mirror image is endsWith().

Before ES2015, a prefix test needed a workaround that hid the intent or had a trap. OrdersPortal uses RET- for return IDs and ORD- for orders:

Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs), or paste it into a browser console. The outputs shown were produced with Node.js 22.23.

const orderId = 'RET-2026-0042';
// Before ES2015: three common workarounds.
console.log(orderId.indexOf('RET-') === 0); // true, but searches the whole string on a miss
console.log(orderId.slice(0, 4) === 'RET-'); // true, but 4 must be kept in sync with the prefix
console.log(/^RET-/.test(orderId)); // true, but a dynamic prefix must be escaped
// ES2015
console.log(orderId.startsWith('RET-')); // true
console.log(orderId.startsWith('2026', 4)); // true: compare from index 4
console.log(orderId.startsWith('ret-')); // false: case-sensitive
// Fragment: signature
str.startsWith(searchString)
str.startsWith(searchString, position)

Following the specification:

  • this is converted to a string; null or undefined throws a TypeError.
  • If searchString is a regular expression, it throws a TypeError; otherwise it is converted to a string.
  • position is converted to an integer and clamped between 0 and the string’s length.
  • An empty searchString returns true immediately. If the prefix would run past the end of the string, the result is false. Otherwise the code units from position are compared with searchString.
console.log('ORD-1'.startsWith('')); // true: empty prefix always matches
console.log('ORD-1'.startsWith('', 50)); // true: even past the end
console.log('ORD-1'.startsWith('ORD', -3)); // true: negative position is clamped to 0
console.log('ORD-1'.startsWith('ORD-1-A')); // false: prefix longer than the string
console.log('ORD-1'.startsWith(['ORD'])); // true: the array becomes "ORD"
console.log('ORD-1'.startsWith(['ORD', 'RET'])); // false: becomes "ORD,RET"
try {
'ORD-1'.startsWith(/^ORD/);
} catch (error) {
console.log(error.constructor.name, '-', error.message);
}

Output:

true
true
true
false
true
false
TypeError - First argument to String.prototype.startsWith must not be a regular expression

Unlike indexOf() === 0, which keeps scanning the rest of the string on a miss, startsWith is defined to compare only the characters at position. The position argument also lets you check for a token after a known prefix without slicing, as in startsWith('2026', 4) above.

OrdersPortal decides which role a request path needs, and validates a returnTo redirect target after login. Both look like prefix checks; only one of them should be.

// route-guard.mjs - classify OrdersPortal request paths and redirect targets.
const SECTIONS = [
{ prefix: '/admin', role: 'admin' },
{ prefix: '/orders', role: 'staff' },
];
// Match whole path segments: "/admin" and "/admin/..." but not "/administrator".
function inSection(path, prefix) {
return path === prefix || path.startsWith(`${prefix}/`);
}
export function requiredRole(path) {
return SECTIONS.find(({ prefix }) => inSection(path, prefix))?.role ?? 'public';
}
for (const path of ['/admin', '/admin/users', '/administrator-guide', '/orders/ORD-1042', '/help']) {
console.log(path.padEnd(22), requiredRole(path));
}
// Redirect allowlist: compare parsed origins, not string prefixes.
const APP_ORIGIN = 'https://portal.example.test';
const naive = (target) => target.startsWith(APP_ORIGIN);
const safe = (target) => {
try {
return new URL(target).origin === APP_ORIGIN;
} catch {
return false; // not an absolute URL
}
};
for (const target of ['https://portal.example.test/orders', 'https://portal.example.test.attacker.test/login']) {
console.log(naive(target), safe(target), target);
}

Output:

/admin admin
/admin/users admin
/administrator-guide public
/orders/ORD-1042 staff
/help public
true true https://portal.example.test/orders
true false https://portal.example.test.attacker.test/login

The naive redirect check accepts a host that merely begins with the same characters, which is an open redirect. A string prefix is the right tool for an already-normalized path; for anything with structure (URLs, file paths with .., email addresses), parse first and compare the parsed parts.

  • Prefix without a boundary. path.startsWith('/admin') is also true for /administrator-guide. Compare the exact value or the prefix plus its separator, as inSection does.
  • Security decisions on raw URLs. url.startsWith('https://portal.example.test') accepts https://portal.example.test.attacker.test. Use new URL(url).origin or .hostname.
  • Passing an array of prefixes. The array is converted to one comma-joined string. Use prefixes.some((p) => str.startsWith(p)).
  • Passing a RegExp. It throws a TypeError. Use /^pattern/.test(str).
  • Assuming case-insensitivity. Lowercase both sides first, or use a regex with the i flag.
  • Forgetting the empty prefix. str.startsWith('') is always true, so a prefix that comes from empty configuration matches everything. Reject empty prefixes when you load them.
Need Use
Fixed prefix, exact case str.startsWith(prefix)
One of several prefixes prefixes.some((p) => str.startsWith(p))
Pattern, alternatives or case-insensitive prefix /^(?:ORD|RET)-/i.test(str)
Suffix endsWith()
Anywhere in the string includes()
Origin, host or path of a URL new URL(str) and compare its parts

According to MDN’s browser compatibility data, String.prototype.startsWith is supported in Chrome 41, Edge 12, Firefox 17, Safari 9 (including iOS), Opera 28, Node.js 4.0.0, Deno 1.0 and Bun 1.0. Internet Explorer never supported it; core-js provides a polyfill.

TypeScript: declared in lib.es2015.core.d.ts as startsWith(searchString: string, position?: number): boolean; any target or lib of ES2015 or later includes it.

1. What does 'abc'.startsWith('') return, and why can that be a bug? true: the spec returns true for an empty search string before comparing anything. If a prefix comes from configuration and is accidentally empty, every value matches.

2. Why is str.startsWith(prefix) better than str.indexOf(prefix) === 0? It states the intent, and it compares only the characters at the start; indexOf keeps searching the rest of the string when the prefix is not at index 0.

3. Senior scenario: a login page accepts ?returnTo= and the code checks returnTo.startsWith('https://portal.example.test'). What is wrong, and how do you fix it? The check accepts any host that begins with those characters, such as portal.example.test.attacker.test, so it is an open redirect. Parse with new URL(returnTo, APP_ORIGIN), require url.origin === APP_ORIGIN, and prefer redirecting to a relative path that you rebuild from the parsed pathname and search. Add tests for look-alike hosts, userinfo (https://portal.example.test@attacker.test) and protocol-relative URLs (//attacker.test).

  • startsWith (ES2015) checks whether the code units at position equal the search string; it is case-sensitive and throws on a RegExp.
  • An empty prefix always matches, and an array argument is joined into one string.
  • For paths, include the separator in the prefix; for URLs, parse and compare origins.
  • Use endsWith for suffixes and includes for “anywhere”.