JavaScript Code


How to check if string starts with specified prefix string using JavaScript?


Check if string starts with specific prefix

Given a string and prefix string, check if the string starts with the prefix string using JavaScript.

Solution

To check if a string starts with a specific prefix string using JavaScript, we can use String.startsWith() method. call startsWith() method on the string, and pass the prefix string as argument.

startsWith() returns true if the string starts with the given prefix string, or false if the string does not start with the given prefix string.

Program

1. given string is str and prefix string is prefix. check if string str starts with prefix

str = "hello world";
prefix = "he";

if ( str.startsWith(prefix) ) {
    console.log('string starts with given prefix');
} else {
    console.log('string does not start with given prefix');
}