String.startsWith() in JavaScript

moazamdev

Moazam Ali

Posted on January 3, 2023

String.startsWith() in JavaScript

The String.prototype.startsWith() method is a string method in JavaScript that returns a Boolean value indicating whether a string starts with a specified search string. This method is case-sensitive, meaning that it will return true only if the search string exactly matches the beginning of the target string.

Syntax

string.startsWith(searchValue, start)
Enter fullscreen mode Exit fullscreen mode
  • searchValue: A specified search string to be searched for at the beginning of the string.
  • start: The position within the string at which to begin searching for searchString. (Defaults to 0.)

It returns a boolean value, true if the searched string is found at the beginning of the given string; otherwise false if not found.

Here's an example of how to use the startsWith() method:

let str = 'Hello, world!';

console.log(str.startsWith('Hello')); // Output: true
console.log(str.startsWith('hello')); // Output: false
Enter fullscreen mode Exit fullscreen mode

In this example, we create a string called str and use the startsWith() method to search for the substring 'Hello' at the beginning of the string. Since the search string exactly matches the beginning of the string, the startsWith() method returns true. However, if we search for the string 'hello', which is not an exact match, the startsWith() method returns false.

The startsWith() method also accepts an optional second argument, which is the index at which the search should start. This is useful if you want to search for a substring within a specific part of the target string.

Here's an example of using the optional second argument:

let str = 'Hello, world!';
console.log(str.startsWith('world', 6)); // Output: true
Enter fullscreen mode Exit fullscreen mode

In this example, we search for the substring 'world' within the string str, starting at the index 6. Since the string 'world' appears at index 7, the startsWith() method returns true.

Wrapping up!

The startsWith() method is a convenient and easy way to check if a string starts with a specified substring in JavaScript. It's often used in combination with other string methods, such as indexOf() and substr(), to perform more complex string operations.

That's all for this article, hope you learned something. Thanks for reading, catch you later.

You can also buy me a coffee that would help me grow as a frontend developer :)

Buy Me A Coffee


πŸ’– πŸ’ͺ πŸ™… 🚩
moazamdev
Moazam Ali

Posted on January 3, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related