Introduction

In JavaScript, the startsWith() method is used to check if a string starts with a specific substring. By calling startsWith() on a string and providing a substring as a parameter, we can determine whether the string starts with that substring or not.

Basic Usage

The startsWith() method can be called on any string variable or string literal. It returns a boolean value (true or false), indicating whether the string starts with the specified substring.

Here’s an example:

'testing'.startsWith('test') // true
'going on testing'.startsWith('test') // false

In the first example, the string “testing” starts with the substring “test”, so startsWith() returns true. In the second example, the string “going on testing” does not start with the substring “test”, so startsWith() returns false.

Specifying the Starting Position

The startsWith() method can also accept a second parameter, which indicates the index at which the checking should start. By default, the method starts checking from the beginning (index 0) of the string.

Here’s an example:

'testing'.startsWith('test', 2) // false
'going on testing'.startsWith('test', 9) // true

In the first example, the startsWith() method starts checking from index 2 of the string “testing”. Since “testing” does not start with the substring “test” at index 2, startsWith() returns false. In the second example, the startsWith() method starts checking from index 9 of the string “going on testing”. Since “going on testing” starts with the substring “test” at index 9, startsWith() returns true.

Conclusion

The startsWith() method in JavaScript is a convenient way to determine whether a string starts with a specific substring. By providing the substring as a parameter, and optionally specifying the starting position, startsWith() can quickly return a boolean value indicating the result.