The startsWith() method in JavaScript is used to determine whether a string begins with the characters of a specified string. It returns 'true' if the string starts with the specified substring, and 'false' otherwise.
Syntax: string.startsWith(searchString, position)
- searchString: The substring to search for at the beginning of the string.
- position (optional): The position within the string at which to begin the search. If omitted, the search starts at index 0.
Example:
let str = "Hello, World!";
let startsWithHello = str.startsWith("Hello");
console.log(startsWithHello); // Output: true
Explanation:
- We have a string str containing "Hello, World!".
- We use startsWith("Hello") to check if the string starts with the substring "Hello".
- The method returns 'true' because the string does indeed start with "Hello".
We can optionally specify a position argument to start the search from a specific index within the string. This can be useful if we want to check if a string starts with a substring but want to ignore certain characters at the beginning.
Code Compiler Link: https://app.singhteekam.in/codecompiler/