Write a JavaScript Program to Check if a String Starts With Another String

When working with strings in JavaScript, it’s common to want to check if one string starts with another string. In this post, we’ll explore how to do that using JavaScript.

To check if a string starts with another string, we can use the startsWith() method.

This method is available on all string objects in JavaScript and takes a single argument, the string we want to check if the current string starts with.

Here’s an example code snippet that demonstrates how to use startsWith():

const str1 = "Hello, world!";
const str2 = "Hello";

if (str1.startsWith(str2)) {
console.log("str1 starts with str2");
} else {
console.log("str1 does not start with str2");
}

In this example, we have two strings, str1 and str2. We use the startsWith() method to check if str1 starts with str2.

If it does, we log a message saying that str1 starts with str2. Otherwise, we log a message saying that str1 does not start with str2.

One thing to keep in mind when using startsWith() is that it is case-sensitive.

This means that if you are checking if a string starts with another string, the case of the characters in both strings must match exactly.

For example, if you’re checking if a string starts with “hello”, but the string starts with “Hello”, startsWith() will return false.

Here’s another example to demonstrate this:

const str3 = "JavaScript is awesome";
const str4 = "javascript";

if (str3.startsWith(str4)) {
console.log("str3 starts with str4");
} else {
console.log("str3 does not start with str4");
}

In this example, we have two strings, str3 and str4. Even though str3 starts with the characters “JavaScript”, which is the same as “javascript” except for the capitalization, startsWith() returns false because the case of the characters does not match.

In conclusion, using the startsWith() method is a simple and effective way to check if a string starts with another string in JavaScript.

However, it’s important to keep in mind that startsWith() is case-sensitive, so the case of the characters in both strings must match exactly for the method to return true.