JavaScript provides various methods for string object manipulation. One of such string methods is the JavaScript StartsWith() i.e., String.prototype.startsWith() function. The JavaScript startsWith() String method checks a particular String type of value against another string and returns if the original string starts with the specified string. The string is a sequence of characters.
In this article, we will learn about JavaScript startswith( ) method with examples. There will be code snippets with output for proper understanding.
JavaScript startswith() takes two parameters:
- The entire string against which the original string is checked.
- The index from which you want to start the searching.
The index/position within string (second parameter) is optional parameter. If you are not providing it the method startswith() JavaScript will start searching the string str from the very beginning, otherwise it will start searching from the specified index.
Table of Contents
Syntax
str.startsWith(stringToBeSearched [, startingPosition])
Return Type
- True: when the specified string is found in the original string.
- False: when the specified string is not found in the original string.
Let’s dive into the implementation of some short coding-based examples to understand the practical working behavior of the JavaScript startsWith() method.
Case#01: JavaScript startsWith() without Specifying the Index Position
In the following example, we are checking a string against two different parameters separately. In the first case, the JavaScript startsWith() function will return true because it will find the matched substring. However, in the second case, it will return false because the original string does not start with the specified substring.
Note: the searching is case-sensitive.
Code
//Case#01: When starting index is not specified
var msg = "It is mostly hot in April ";
var result = msg.startsWith("It");
console.log(result);
result = msg.startsWith("hot");
console.log(result);
Output

Case#02: JavaScript startsWith() with the Index Position
The example below will check a substring from the original message, but this time we are telling the method a starting position (index) to begin the search. If the string being searched is found on the specified index value, the JavaScript StartsWith Method will return true, otherwise false.
Code
//Case#02: When starting index is specified
var msg = "It is mostly hot in April";
var result = msg.startsWith("April", 20);
console.log(result);
result = msg.startsWith("hot", 23);
console.log(result);
Output

Conclusion
In this short tutorial, we discussed the JavaScript String.prototype.startsWith() method and how it can be used to manipulate a string object. It basically checks for a string within another string with the help of two parameters, out of which one is mandatory, and the other one is optional. It returns a Boolean value to the user indicating the existence of the substring within the string.