Summary: in this tutorial, you will learn how to use the JavaScript String startsWith()
method to perform a case-sensitive search and determine if a string starts with a substring.
Introduction to the JavaScript String startsWith() method
The startsWith()
returns true
if a string starts with a substring or false
otherwise.
Here’s the syntax of the startsWith()
method:
String.startsWith(searchString [,position])
Code language: JavaScript (javascript)
In this syntax:
searchString
is a substring to search for within the string.position
is an optional parameter that determines the starting position to search for thesearchString
.
The position
defaults to 0. This means that the method starts searching for the searchString
from the beginning of the string.
Like other string methods, the startsWith()
method always performs a case-sensitive search.
The startsWith()
method throws a TypeError
if the searchString is a regular expression.
JavaScript String startsWith() method examples
Let’s take some examples of using the startsWith()
method.
Basic JavaScript String startsWith() method
The following example uses the startsWith()
method to check if the string "Jack and Jill Went Up the Hill"
starts with the substring 'Jack'
:
const title = "Jack and Jill Went Up the Hill";
const result = title.startsWith("Jack");
console.log({ result });
Code language: JavaScript (javascript)
Output:
{ result: true }
Code language: CSS (css)
Case-sensitive search example
The startsWith()
method always performs a case-sensitive search, so the following statement returns false
:
const title = "Jack and Jill Went Up the Hill";
const result = title.startsWith("jack");
console.log({ result });
Code language: JavaScript (javascript)
Output:
{ result: false }
Code language: CSS (css)
Using the position parameter
This example uses the startsWith()
method with the second parameter that specifies the beginning position to start searching:
const title = "Jack and Jill Went Up the Hill";
const result = title.startsWith("Jill", 9);
console.log({ result });
Code language: JavaScript (javascript)
Output:
{ result: true }
Code language: CSS (css)
Throwing a TypeError
The following example throws a TypeError
because the searchString
is a regular expression:
const str = "JavaScript";
const result = str.startsWith(/J/);
console.log({ result });
Code language: JavaScript (javascript)
Output:
TypeError: First argument to String.prototype.startsWith must not be a regular expression
Code language: JavaScript (javascript)
Summary
- Use JavaScript String
startsWith()
method to perform a case-sensitive search and check if a string starts with a substring.