DEV Community

hrishikesh1990
hrishikesh1990

Posted on • Originally published at flexiple.com

How to use the JavaScript startsWith() method?

In this short tutorial, we look at how to use the JavaScript startsWith method. We break down the code with an example to help you understand the concept better.

Table of Contents - JavaScript startsWith():

What does startsWith do in JavaScript?

The JavaScript startsWith method is used to determine whether a string starts with a character or a particular string. The method returns a boolean true in case the string starts with the specified characters.

This method is commonly used to check if the entered string contains a substring. Although there are other methods that can be used to find substrings, the startsWith() method is specifically used to check the start of a string.

Syntax:

startsWith(SearchString)
Enter fullscreen mode Exit fullscreen mode

Parameters

  • SearchString - Required, the character/ string to search
  • Position - Optional, used to specify the position to begin the search ### Return Value: The method returns a boolean true if it finds the SearchString and false if it doesn’t.

Code and Explanation:

In this section, we look at the implementation of the startsWith method.

const str_1 = 'Join our freelancer community';

console.log(str_1.startsWith('Join'));
// Output: true

console.log(str_1.startsWith('Join', 3));
// Output: false

console.log(str_1.startsWith('our', 5));
// Output: true
Enter fullscreen mode Exit fullscreen mode

In the above code, the first statement returns true as the string begins with ‘Join”. However, in the second statement, we have passed a position argument. Hence the startsWith operator starts searching from the 3 index and returns a false.

Similarly, the last statement returns true as ‘our’ start’s in the 5th index.

Closing thoughts - JavaScript startsWith:

A major caveat while using the startsWith method is that it is case-sensitive. Unlike the includes() method in JavaScript, the startsWith method is used specifically to find if a string starts with a string.

However, in case you are just looking to find a substring, I would recommend using the includes() method.

Once you are done practicing using the startsWith methods you can try the endsWith method.

Top comments (0)