Using the startsWith() Method in JavaScript

The startsWith() method in JavaScript is used to check whether a string begins with the specified characters. This method returns a Boolean value, indicating whether the string begins with the specified characters or not.

Here is an example of how to use the startsWith() method:

var str = "Hello, world!";
if (str.startsWith("Hello")) {
console.log("The string begins with 'Hello'");
}

In this example, the startsWith() method is used to check if the string str begins with the string "Hello". If it does, then a message is logged to the console.

Note that the startsWith() method is case-sensitive, so the following code would not produce the same result:

if (str.startsWith("hello")) {
console.log("The string begins with 'hello'");
}

In this case, the startsWith() method would return false, because the string "Hello, world!" does not begin with the string "hello" (the h is capitalized in the original string).


December 04, 2022
248