JavaScript(JS) JS check if a string starts with another string

www.igift‮edi‬a.com

In JavaScript, you can check whether a string starts with another string using the startsWith() method. Here's an example:

const myString = 'Hello World';
const prefixString = 'Hello';

if (myString.startsWith(prefixString)) {
  console.log(`'${myString}' starts with '${prefixString}'`);
} else {
  console.log(`'${myString}' does not start with '${prefixString}'`);
}

In the above example, we declare the string myString and the string we want to check if it is the prefix prefixString.

We then use the startsWith() method to check whether myString starts with prefixString. If it does, the code inside the if block will execute. If it doesn't, the code inside the else block will execute.

Note that the startsWith() method is case sensitive. If you want to perform a case-insensitive comparison, you can convert both strings to lowercase or uppercase using the toLowerCase() or toUpperCase() methods before calling startsWith().