Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 20, 2021 12:38 pm GMT

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)

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 doesnt.

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: trueconsole.log(str_1.startsWith('Join', 3));// Output: falseconsole.log(str_1.startsWith('our', 5));// Output: true

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 starts 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.


Original Link: https://dev.to/hrishikesh1990/how-to-use-the-javascript-startswith-method-2e4h

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To