JavaScript String startsWith() method checks if a string begins with the characters of a specified string, returning true if the substring is found at the start (or specified position), and false otherwise. It is a case-sensitive method.
const text = "Hi AppDividend"; output = text.startsWith("Hi"); console.log(output); // Output: true
In this code, the input text starts with “Hi”, and that’s why it returns true.
If we have passed “App” as an argument, it returns false because it does not start with that specific part.
const text = "Hi AppDividend"; output = text.startsWith("App"); console.log(output); // Output: true
Syntax
string.startsWith(search_string, position)
Parameters
Argument | Description |
search_string (required) |
It represents the substring to search for at the beginning of the string. If you omit this argument or undefined, it searches for the string “undefined”. Passing a RegExp will throw a TypeError. |
position (optional) |
It is a non-negative integer suggesting the position from which to begin the search (zero-based index). |
Passing a “position” parameter
If you want to start searching from a specific position, you need to pass that position’s index in the second argument, effectively checking a substring’s prefix.
const text = "Hi AppDividend"; output = text.startsWith("Div", 6); console.log(output); // Output: true
It is really helpful for parsing delimited strings or skipping known prefixes.
Case Sensitivity
The String.startsWith() is a case-sensitive function, and it returns false if the string values are the same but the cases are different.
const text = "Hello"; output = text.startsWith("hel"); console.log(output); // Output: false
Empty search string
If the search string is empty, it always matches, as an empty prefix exists at any position.
const text = "Hi AppDividend"; output = text.startsWith(""); console.log(output); // Output: true
In this case, developers should handle empty inputs explicitly to avoid unintended true results in validation logic.
Negative or invalid position
If you pass the negative positions, it is clamped to 0.
In other words, text.startsWith(“Hi”, -1) is equivalent to text.startsWith(“Hi”, 0). Both will return true in our case.
const text = "Hi AppDividend"; output = text.startsWith("Hi", -1); console.log(output); // Output: true
That’s all!