The startsWith()
method in JavaScript is a string method that determines whether a string begins with the characters of a’specified substring. It returns a boolean value: true
if the string starts with the substring, and false
if it doesn’t. This method is case-sensitive, meaning it distinguishes between uppercase and lowercase letters, and it can accept an optional parameter to specify the starting position for the check within the string. Introduced in ECMAScript 6 (ES2015), startsWith()
is widely supported across modern browsers, Node.js environments, and JavaScript runtimes, making it a reliable tool for string manipulation.
Syntax
string.startsWith(searchString[, position])
searchString
: The substring to search for at the beginning of the string. This can be a single character, a word, or any sequence of characters.position
(optional): An integer representing the index at which to begin checking for thesearchString
. If omitted, it defaults to0
. If the position is negative, it is treated as0
. If the position is greater than or equal to the string’s length, the method returnsfalse
.
Return Value
true
: If the string begins withsearchString
at the specified position.false
: If it does not.
Detailed Behavior
- Case Sensitivity:
ThestartsWith()
method performs a case-sensitive comparison. For example,"Hello".startsWith("hello")
returnsfalse
because the capitalization doesn’t match. - Position Parameter:
Theposition
parameter allows you to skip a portion of the string and start the check at a specific index. This is useful for checking substrings within a string. For instance:
const str = "JavaScript is fun";
console.log(str.startsWith("Script", 4)); // true
Here, the check begins at index 4, where “Script” starts.
- Edge Cases:
- If
searchString
is an empty string (""
),startsWith()
returnstrue
for any valid position within or at the end of the string:javascript console.log("Hello".startsWith("")); // true console.log("Hello".startsWith("", 5)); // true
- If
position
is greater than or equal to the string’s length, the method returnsfalse
unlesssearchString
is empty:javascript console.log("Hello".startsWith("H", 10)); // false console.log("Hello".startsWith("", 10)); // true
- If
position
is negative orNaN
, it is treated as0
:javascript console.log("Hello".startsWith("H", -5)); // true console.log("Hello".startsWith("H", NaN)); // true
- If the input string or
searchString
is not a string, JavaScript will attempt to coerce it to a string:javascript console.log("123".startsWith(1)); // true (1 is coerced to "1")
- Type Coercion:
Non-string arguments forsearchString
are converted to strings using theirtoString()
method. For example:
console.log("true".startsWith(true)); // true (true is coerced to "true")
console.log("123".startsWith(123)); // true (123 is coerced to "123")
Examples
Here are various scenarios demonstrating startsWith()
:
Basic Usage
const str = "To be, or not to be, that is the question.";
console.log(str.startsWith("To")); // true
console.log(str.startsWith("not")); // false
console.log(str.startsWith("to")); // false (case-sensitive)
Using the Position Parameter
const sentence = "The quick brown fox";
console.log(sentence.startsWith("quick", 4)); // true
console.log(sentence.startsWith("The", 0)); // true
console.log(sentence.startsWith("The", 1)); // false
Edge Cases
const text = "Hello, world!";
console.log(text.startsWith("")); // true (empty string)
console.log(text.startsWith("H", 100)); // false (position exceeds length)
console.log(text.startsWith("H", -1)); // true (negative position treated as 0)
console.log(text.startsWith(undefined)); // false (undefined coerced to "undefined")
Practical Use Case: Filtering
startsWith()
is often used to filter arrays or validate input. For example:
const fruits = ["apple", "banana", "apricot", "cherry"];
const startsWithA = fruits.filter(fruit => fruit.startsWith("a"));
console.log(startsWithA); // ["apple", "apricot"]
Combining with Other Methods
You might use startsWith()
with other string methods for more complex checks:
const url = "https://example.com";
if (url.startsWith("https")) {
console.log("Secure URL"); // Secure URL
} else if (url.startsWith("http")) {
console.log("Non-secure URL");
}
Performance Considerations
- Time Complexity: The
startsWith()
method has a time complexity of O(n), wheren
is the length of thesearchString
, as it compares characters one by one. - Efficiency: For simple prefix checks,
startsWith()
is optimized and faster than alternatives like usingsubstring()
or regular expressions (e.g.,/^searchString/
). - Comparison with Alternatives:
- Using
str.slice(0, searchString.length) === searchString
is less readable and slightly slower. - Regular expressions like
str.match(/^searchString/)
are overkill for simple prefix checks and less performant.
Browser and Environment Support
- Browsers: Supported in all modern browsers (Chrome, Firefox, Safari, Edge) since 2015.
- Node.js: Available in all versions still in active support.
- Polyfills: For older environments (e.g., IE), you can use a polyfill:
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
This uses indexOf()
to achieve the same result, though it’s less performant.
Common Use Cases
- Input Validation:
- Check if a phone number starts with a specific country code:
javascript const phone = "+12025550123"; console.log(phone.startsWith("+1")); // true
- Validate URLs or protocols:
javascript const url = "ftp://server.com"; console.log(url.startsWith("http")); // false
- Search and Filtering:
- Filter autocomplete suggestions:
javascript const suggestions = ["cat", "car", "dog"]; const query = "ca"; const matches = suggestions.filter(item => item.startsWith(query)); console.log(matches); // ["cat", "car"]
- Parsing Data:
- Process CSV headers or structured text:
javascript const line = "ID,Name,Age"; if (line.startsWith("ID")) { console.log("Valid CSV header"); }
Limitations
- Case Sensitivity: If you need case-insensitive checks, you must normalize the strings first (e.g., convert both to lowercase):
const str = "Hello";
console.log(str.toLowerCase().startsWith("hello")); // true
- No Regular Expressions:
startsWith()
doesn’t support regex patterns. For pattern-based checks, usematch()
ortest()
:
const str = "123abc";
console.log(/^\d/.test(str)); // true (starts with a digit)
- Unicode Characters:
startsWith()
handles Unicode correctly, but be cautious with emoji or complex scripts where character boundaries might be tricky:
const emoji = "😊smile";
console.log(emoji.startsWith("😊")); // true
Related Methods
endsWith()
: Checks if a string ends with a specified substring.
console.log("Hello".endsWith("lo")); // true
includes()
: Checks if a substring exists anywhere in the string.
console.log("Hello".includes("ell")); // true
indexOf()
: Returns the index of the first occurrence of a substring (or-1
if not found).
console.log("Hello".indexOf("H") === 0); // true (mimics startsWith)
Practical Tips
- Combine with Trim: If dealing with user input, trim whitespace to avoid false negatives:
const input = " Hello";
console.log(input.trim().startsWith("Hello")); // true
- Dynamic Prefixes: When checking multiple prefixes, use an array and
some()
:
const prefixes = ["http", "https", "ftp"];
const url = "https://example.com";
console.log(prefixes.some(p => url.startsWith(p))); // true
Debugging Common Issues
- Unexpected
false
: Double-check case sensitivity or leading/trailing spaces. - Position Misuse: Ensure the
position
parameter isn’t larger than the string length unless checking for an empty string. - Non-String Inputs: If
startsWith()
behaves oddly, verify that inputs are strings or understand coercion effects:
console.log(null.startsWith("n")); // TypeError: null is not a string