Description
The JavaScript String method startsWith()
checks if a string starts with a specific text.
- The method returns
true
if the string starts with a given text, otherwise returnsfalse
. - The method is case-sensitive.
Syntax
The method startsWith()
has the below syntax, where str
is a string.
str.startsWith(searchString, startIndex)
Parameters
The method startsWith()
allows the below parameters.
searchString
- It is a character(s) to be searched for at the beginning of the string
str
.
startIndex
(optional)
- It defines the beginning index to start searching for the string
searchString
. - The default value is
0
, which means from the beginning of the stringstr
.
Result
Returns true
if the string str
starts with searchString
. Otherwise returns false
.
Example 1: Using the Method
The below example shows the basic usage of the method.
var str = "Learning JavaScript is fun";
// Returns true
document.write(str.startsWith("")); // Prints: true
document.write(str.startsWith("Learn")); // Prints: true
document.write(str.startsWith("Learning")); // Prints: true
document.write(str.startsWith("Learning JavaScript")); // Prints: true
// Returns false
document.write(str.startsWith("JavaScript")); // Prints: false
document.write(str.startsWith("fun")); // Prints: false
document.write(str.startsWith("hello")); // Prints: false
Output:
true
true
true
true
false
false
false
Example 2: Method is Case-Sensitive
The method is case-sensitive, so it returns true only if both the text and its case are matched.
var str = "Learning JavaScript is fun";
// Case matching
document.write(str.startsWith("Learning")); // Prints: true
// Case not matching
document.write(str.startsWith("learning")); // Prints: false
Output:
true
false
Example 3: Using the Method with Position
If we need to check if a string contains a specific text at a specific index, we can use the position
parameter.
var str = "Learning JavaScript is fun";
// Case matching
document.write(str.startsWith("Learning", 9)); // Prints: false
// Case not matching
document.write(str.startsWith("JavaScript", 9)); // Prints: true
Output:
false
true
Overall
The JavaScript String method startsWith()
checks if a string starts with a specific text.