String.prototype.startsWith(): check a prefix (ES2015)
What you’ll learn
Section titled “What you’ll learn”- What
String.prototype.startsWith()returns and what itspositionargument does. - The edge cases: empty prefixes, clamping, coercion and the
TypeErrorfor a regular expression. - How to match path prefixes by whole segment, and several prefixes at once.
- Why
startsWithon a URL string is not a security check.
Summary
Section titled “Summary”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().
The problem it solves
Section titled “The problem it solves”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 missconsole.log(orderId.slice(0, 4) === 'RET-'); // true, but 4 must be kept in sync with the prefixconsole.log(/^RET-/.test(orderId)); // true, but a dynamic prefix must be escaped
// ES2015console.log(orderId.startsWith('RET-')); // trueconsole.log(orderId.startsWith('2026', 4)); // true: compare from index 4console.log(orderId.startsWith('ret-')); // false: case-sensitiveHow it works
Section titled “How it works”// Fragment: signaturestr.startsWith(searchString)str.startsWith(searchString, position)Following the specification:
thisis converted to a string;nullorundefinedthrows aTypeError.- If
searchStringis a regular expression, it throws aTypeError; otherwise it is converted to a string. positionis converted to an integer and clamped between0and the string’s length.- An empty
searchStringreturnstrueimmediately. If the prefix would run past the end of the string, the result isfalse. Otherwise the code units frompositionare compared withsearchString.
console.log('ORD-1'.startsWith('')); // true: empty prefix always matchesconsole.log('ORD-1'.startsWith('', 50)); // true: even past the endconsole.log('ORD-1'.startsWith('ORD', -3)); // true: negative position is clamped to 0console.log('ORD-1'.startsWith('ORD-1-A')); // false: prefix longer than the stringconsole.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:
truetruetruefalsetruefalseTypeError - First argument to String.prototype.startsWith must not be a regular expressionUnlike 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.
Realistic example
Section titled “Realistic example”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 publictrue true https://portal.example.test/orderstrue false https://portal.example.test.attacker.test/loginThe 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.
Common mistakes
Section titled “Common mistakes”- Prefix without a boundary.
path.startsWith('/admin')is also true for/administrator-guide. Compare the exact value or the prefix plus its separator, asinSectiondoes. - Security decisions on raw URLs.
url.startsWith('https://portal.example.test')acceptshttps://portal.example.test.attacker.test. Usenew URL(url).originor.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
iflag. - Forgetting the empty prefix.
str.startsWith('')is alwaystrue, so a prefix that comes from empty configuration matches everything. Reject empty prefixes when you load them.
When to use it and when not to
Section titled “When to use it and when not to”| 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 |
Compatibility
Section titled “Compatibility”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.
Interview questions
Section titled “Interview questions”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).
Key takeaways
Section titled “Key takeaways”startsWith(ES2015) checks whether the code units atpositionequal 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
endsWithfor suffixes andincludesfor “anywhere”.
Related pages
Section titled “Related pages”- String.prototype.endsWith(): the suffix counterpart.
- String.prototype.includes(): substring anywhere in the string.
- String.prototype.padStart(): add characters to the start of a string.
- Template literals: used to build the prefix with its separator above.
- Regular expressions: anchored patterns with
^. - JavaScript interview questions