Checking if a string starts with another substring is a common task in JavaScript. In this article, we will explore how to perform this check efficiently using the startsWith()
method introduced in ES6.
ES6, released in 2015, introduced the startsWith()
method, making it easier to check if a string starts with a specified substring. This method is now the preferred approach in modern JavaScript.
To use startsWith()
, simply call the method on any string instance and pass in the substring you want to check. The method will return true
if the string starts with the specified substring, or false
otherwise.
Here are a couple of examples to illustrate its usage:
'testing'.startsWith('test'); // true
'going on testing'.startsWith('test'); // false
In addition, startsWith()
supports an optional second parameter that specifies the index at which to start the comparison. This can be useful when you want to skip a certain number of characters before checking for a match.
'testing'.startsWith('test', 2); // false
'going on testing'.startsWith('test', 9); // true
By utilizing the startsWith()
method, you can easily and efficiently check if a string starts with another in JavaScript.