The startsWith() method of the String class in JavaScript determines whether a string begins with the characters of a specified string, returning true or false as appropriate.
There are 2 variations for the syntax of String.startsWith() method. They are:
startsWith(searchString)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
searchString | required | The characters to be searched for at the start of this string. |
This method checks if the string starts with the specified searchString.
Returns value of type Boolean
.
startsWith(searchString, position)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
searchString | required | The characters to be searched for at the start of this string. |
position | optional | The position in this string at which to begin searching for searchString. Defaults to 0. |
This method checks if the string starts with the specified searchString at the given position.
Returns value of type Boolean
.
In JavaScript, we can use the startsWith()
method to check if a string starts with a specified substring.
For example,
str
with the value 'Hello, world!'
.startsWith()
method with the search string 'Hello'
.'Hello'
, is stored in the variable result
.result
to the console using console.log()
method.const str = 'Hello, world!';
const result = str.startsWith('Hello');
console.log(result);
true
In this example, we use the startsWith()
method to check if a string starts with a specified substring at a given position.
For example,
str
with the value 'Hello, world!'
.startsWith()
method with the search string 'world'
and the position 7
.'world'
at position 7
, is stored in the variable result
.result
to the console using console.log()
method.const str = 'Hello, world!';
const result = str.startsWith('world', 7);
console.log(result);
true
In this example, we use the startsWith()
method to check if a string starts with a specified substring, without specifying a position (defaults to 0).
For example,
str
with the value 'JavaScript'
.startsWith()
method with the search string 'Java'
.'Java'
, is stored in the variable result
.result
to the console using console.log()
method.const str = 'JavaScript';
const result = str.startsWith('Java');
console.log(result);
true
In this JavaScript tutorial, we learned about startsWith() method of String: the syntax and few working examples with output and detailed explanation for each example.