3

How to use the JavaScript startsWith() method?

 2 years ago
source link: https://dev.to/hrishikesh1990/how-to-use-the-javascript-startswith-method-2e4h
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK