String.prototype.startsWith()
startsWith(searchString[, position]) The startsWith() method determines whether a string begins with the characters of a specified search string. It returns true if the string starts with the search string, and false otherwise. This method is case-sensitive and was introduced in ES6 as a cleaner alternative to manual prefix checking using indexOf() or substring comparisons.
One important detail: the method treats all non-regex values as strings through type coercion, so passing undefined will search for the literal string “undefined” rather than behaving as you might expect.
Syntax
string.startsWith(searchString)
string.startsWith(searchString, position)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
searchString | string | — | The characters to search for at the start of the string. Cannot be a regex. All values are coerced to strings. |
position | number | 0 | The start position at which searchString is expected to be found. Defaults to 0, meaning the beginning of the string. |
Parameter Details
- If
searchStringis an empty string, the method always returnstrue. - Passing
undefinedassearchStringsearches for the string “undefined” — this is rarely the intended behavior. - The
positionparameter specifies where to start the search, but it’s the index in the original string where the search begins, not an offset into the search string. - A
TypeErroris thrown ifsearchStringis a regular expression.
Examples
Basic prefix checking
const str = "Saturday night plans";
console.log(str.startsWith("Sat")); // true
console.log(str.startsWith("sat")); // false (case-sensitive)
console.log(str.startsWith("night")); // false
The most common use case is validating whether a string begins with a specific prefix. Here, “Sat” matches but the lowercase variant doesn’t because the method is case-sensitive.
The return value is a simple boolean, which makes startsWith() a natural fit for conditional logic. You can guard an operation, route a request, or toggle a feature flag based on whether a particular prefix appears at the start of a string.
Using the position parameter
const str = "To be, or not to be, that is the question.";
console.log(str.startsWith("To be")); // true
console.log(str.startsWith("To be", 0)); // true (explicit start)
console.log(str.startsWith("not to be")); // false
console.log(str.startsWith("not to be", 10)); // true
console.log(str.startsWith("To be", 1)); // false
The position parameter lets you check for a prefix starting from a specific index. When you pass 10, it looks at the substring starting at position 10 (“not to be, that is the question.”), which does begin with “not to be”. This is useful when parsing structured strings or validating segments.
A common pitfall with the position argument is forgetting that it shifts where the search begins in the original string, not where the search string is trimmed. The full original string is still considered; only the starting index changes.
Checking protocol and file types
const url = "https://example.com/api/users";
console.log(url.startsWith("https://")); // true
console.log(url.startsWith("http://")); // false
const filename = "report-2024.pdf";
console.log(filename.startsWith("report")); // true
console.log(filename.endsWith(".pdf")); // true
A practical application is validating URL protocols or file extensions. Combining startsWith() with endsWith() gives you a simple way to check both prefix and suffix.
This pattern is especially handy in server-side JavaScript where you receive URLs, filenames, or user-supplied paths and need to classify them before taking action. A single if statement with startsWith() replaces what would otherwise be a substring extraction followed by a comparison.
Working with dynamic content
function formatMessage(type, text) {
const prefix = `[${type.toUpperCase()}]`;
if (text.startsWith(prefix)) {
return text; // Already formatted
}
return `${prefix} ${text}`;
}
console.log(formatMessage("info", "System ready")); // "[INFO] System ready"
console.log(formatMessage("info", "[INFO] Duplicate")); // "[INFO] Duplicate"
When building logging or messaging systems, you often need to check if content is already formatted before applying formatting. This pattern prevents double-formatting.
The function also demonstrates a useful design choice: when the text already carries the prefix, returning it as-is avoids redundant work and keeps log output clean. If you were building a chat client or an error reporter, this same guard would stop message prefixes from stacking up across multiple processing stages.
Common Patterns
The following patterns show how startsWith() supports common string-processing workflows. Each one replaces a longer, less readable alternative with a one-liner that states the intent clearly.
Validating command input:
const commands = ["help", "status", "exit"];
function isValidCommand(input) {
return commands.some(cmd => input.startsWith(cmd));
}
console.log(isValidCommand("help me")); // true
console.log(isValidCommand("status")); // true
console.log(isValidCommand("restart now")); // false
Command validation with startsWith() lets users type partial commands and still get the right behavior. Without it, you would need an exact-match lookup table that forces users to type every character correctly. The some() method returns true as soon as any command prefix matches, so validation stops early for valid inputs. This approach scales cleanly — add a new command to the array and the function handles it without modification.
Safe string concatenation:
function addPrefixIfNeeded(str, prefix) {
return str.startsWith(prefix) ? str : prefix + str;
}
console.log(addPrefixIfNeeded("users", "role:")); // "role:users"
console.log(addPrefixIfNeeded("role:admins", "role:")); // "role:admins"
The conditional operator keeps the call-site compact. For namespace-style prefixes like "role:", this pattern avoids the bug where you accidentally double the prefix — a mistake that is easy to miss in log output until it shows up in production.
Filtering arrays by prefix:
const items = ["apple", "apricot", "banana", "blueberry"];
const filtered = items.filter(item => item.startsWith("a"));
console.log(filtered); // ["apple", "apricot"]
Array filtering with startsWith() is a natural fit for autocomplete suggestions, file pickers, and search-as-you-type interfaces. It runs in linear time and reads more clearly than a for loop with a manual index check.
Checking string prefixes in conditional logic:
const userInput = "delete-all";
if (userInput.startsWith("delete-")) {
console.log("⚠️ This is a destructive command");
} else if (userInput.startsWith("get-")) {
console.log("📤 This is a read operation");
}
Next Steps
Now that you understand how to check if a string begins with a specific prefix, explore other string methods for different types of matching. If you need to check the end of a string instead, endsWith() provides the opposite functionality. For finding substrings anywhere in the string, includes() is the method you want.
For more complex pattern matching beyond simple prefix checks, consider using regular expressions with the match() or test() methods. However, for straightforward prefix validation, startsWith() offers better readability and intentionality in your code.
See Also
- String.includes() — Check if a string contains a substring anywhere
- String.slice() — Extract a portion of a string