Does an address begin with https://, a path with /admin, a role with ROLE_: these checks happen dozens of times in an application, often at the moment of deciding who is allowed to see what.
startsWith and its mirror endsWith answer with true or false, with no detour through an index to compare.
Definition
startsWith(text) hands back true when the String begins exactly with the given text. endsWith(text) runs the same check at the end.
const url = "https://believemy.com/en/glossaries";
console.log(url.startsWith("https://")); // true
console.log(url.startsWith("http://")); // false
console.log(url.endsWith("/glossaries")); // true
console.log("report.pdf".endsWith(".pdf")); // trueBoth methods always hand back a boolean, which makes them usable straight inside an if or a Array.filter().
Case matters, and the position can be moved
The comparison is exact. One capital letter of difference is enough to get false, which is what you want on a technical prefix and a nuisance on typed text.
console.log("Hello".startsWith("hello")); // false
console.log("Hello".toLowerCase().startsWith("hello")); // true
console.log("abcdef".startsWith("cd", 2)); // true, the check starts at index 2The second argument of startsWith moves the starting point, the one on endsWith does the opposite: it states where the string should be considered to end. "abcdef".endsWith("cd", 4) therefore hands back true, since only the first four characters are examined.
Where these methods really earn their place
- Securing a redirect by checking the address begins with your own domain, rather than following it blindly.
- Routing a request by testing whether the path begins with
/adminor with a language code. - Filtering files with
endsWithon the extension, which stays more readable than cutting on the dot. - Recognizing a business prefix such as
ROLE_orcus_, very common in API identifiers.
const files = ["course.pdf", "notes.txt", "invoice.pdf"];
console.log(files.filter((f) => f.endsWith(".pdf"))); // [ 'course.pdf', 'invoice.pdf' ]Frequently asked questions
startsWith or indexOf(text) === 0?
The result is the same, the readability is not. startsWith says what it does, where the comparison against zero costs a beat of reading and invites the inverted logic described in indexOf(). The older form is only justified on very old environments.
Can it take a regular expression?
No, and the error is explicit: a TypeError is raised when the first argument is a RegExp. To test a beginning with a pattern, use the expression's test method, with the ^ anchor meaning "start of string".
How do you test several prefixes at once?
By putting the list in an array and asking with Array.some(): prefixes.some((p) => path.startsWith(p)). The same form with every would check that all prefixes match, which obviously makes no sense here, since a string has only one beginning.