JavaScript startsWith() method
The startsWith()
method in JavaScript is used to determine whether a string begins with a specified substring. This method is particularly useful for checking if a string starts with a certain word or sequence of characters.
Syntax:
searchString
: The substring to search for at the start of the string. This is a required parameter.position
(optional): The position in the string at which to begin searching. The default value is0
, meaning the search starts at the beginning of the string.
Return Value:
- Returns
true
if the string starts with the specified substring; otherwise, it returnsfalse
.
Example 1: Basic Usage
In this example, the method checks if the string starts with "Hello"
and returns true
.
Example 2: Checking a Different Position
You can specify a different position from which to start the search.
Here, the method checks if the string starting from index 7
begins with "World"
, and it returns true
.
Example 3: Case Sensitivity
The startsWith()
method is case-sensitive.
In this example, the search for "hello"
(lowercase) returns false
because it does not match the uppercase "H"
.
Example 4: Position Out of Range
If the position
specified is greater than the length of the string, startsWith()
will always return false
.
In this case, since the starting position 15
exceeds the length of the string, the method returns false
.
Example 5: Using Empty Strings
An empty string is considered to start with any other string, including itself.
In this example, both checks return true
because every string, including an empty string, starts with an empty string.
Example 6: Checking for Non-String Values
If a non-string value is passed as the searchString
, it is converted to a string using the String()
function.
In this case, the number Hello
is implicitly converted to the string "Hello"
before the comparison is made.
Summary:
- The
startsWith()
method checks if a string begins with a specified substring. - It takes two parameters:
searchString
(required) andposition
(optional). - The method is case-sensitive and returns
true
orfalse
based on whether the substring is found at the beginning of the string. - An empty string will always return
true
when checked withstartsWith()
, and non-string values are converted to strings for comparison.