JavaScript – Check if String starts with Specific Substring

To check if a string str starts with a specific string searchStr in JavaScript, call startsWith() method on this string str, and pass the other string searchStr as argument.

startsWith() method returns a boolean value. The return value is true if specified string is present at the start of this string, or else, it returns false.

Syntax

The syntax to check if string str1 starts with the string searchStr is

str.startsWith(searchStr)
ADVERTISEMENT

Examples

The following is a quick example to check if string str1 starts with the string searchStr in JavaScript.

var str = 'Hello World';
var searchStr = 'Hel';
var result = str.startsWith(searchStr);

We may use the return value of startsWith() method as a condition in If statement.

var str = 'Hello World';
var searchStr = 'Hel';
if ( str.startsWith(searchStr) ) {
    //str starts with specified searchStr
} else {
    //str does not start with specified searchStr
}

In the following example, we take two strings: str and searchStr in script, and check if string str starts with the string searchStr using startsWith() method. We shall display the result in a div.

index.html

Conclusion

In this JavaScript Tutorial, we learned how to check if a string starts with a specified string in JavaScript, using startsWith() method, with examples.