JavaScript String startsWith()
startsWith()
method to check if a string starts with a substring.Introduction to the JavaScript startsWith() method
The startsWith()
returns true
if a string starts with a substring or false
otherwise.
The following shows the syntax of the startsWith()
method:
String.startsWith(searchString [,position])
Code language: CSS (css)
Arguments
searchString
is the characters to be searched for at the start of this string.position
is an optional parameter that determines the start position to search for thesearchString
. It defaults to 0.
JavaScript String startsWith() examples
Suppose that you have a string called title
as follows:
const title = 'Jack and Jill Went Up the Hill';
Code language: JavaScript (javascript)
The following example uses the startsWith()
method to check if the title
starts with the string 'Jack'
:
console.log(title.startsWith('Jack'));
Code language: JavaScript (javascript)
Output:
true
Code language: JavaScript (javascript)
The startsWith()
method matches characters case-sensitively, so the following statement returns false
:
title.startsWith('jack');
Code language: JavaScript (javascript)
This example uses the startsWith()
method with the second parameter that determines the beginning position to start searching:
console.log(title.startsWith('Jill', 9));
Code language: JavaScript (javascript)
Output:
true
Code language: JavaScript (javascript)
Put it all together:
const title = 'Jack and Jill Went Up the Hill';console.log(title.startsWith('Jack'));
console.log(title.startsWith('jack'));
console.log(title.startsWith('Jill', 9));
Code language: JavaScript (javascript)
Output:
true
false
true
Code language: JavaScript (javascript)
Summary
- Use the String startsWith() method to check if a string starts with a substring.