JavaScript startsWith()
The startsWith()
method in JavaScript is a string function that checks whether a string starts with the characters of a specified string. This method returns true if the given string matches the start of the string being checked, and false otherwise.
Syntax
The syntax for startsWith()
method is as follows:
string.startsWith(searchString[, position])
Here, string
is the original string, searchString
is the string to be searched at the beginning of the original string and position
(optional) is an integer value that specifies the index to start the search.
Example
Consider the following example:
const str = 'Hello, World!';
console.log(str.startsWith('Hello')); // Output: true
console.log(str.startsWith('hello')); // Output: false
console.log(str.startsWith('World', 7)); // Output: true
In the first example, startsWith()
returns true
because the string 'Hello'
is indeed at the beginning of str
. In the second example, startsWith()
returns false
because 'hello'
is not the same as 'Hello'
. Finally, in the third example, startsWith()
searches for 'World'
in str
starting from index 7
and returns true
because 'World'
is the first word at index 7
.
Output
The output of the startsWith()
method is either true
or false
, depending on whether the specified string is at the start of the original string.