Using the JavaScript String startsWith() method, we can check to see if a string starts with a certain character or string. The startsWith method is used on a string and takes a string as its parameter.

someString.startsWith("anotherString");

Let’s take a look at an example of this below.


Let’s say we have the following JavaScript:

var someString = "This is some example text";

If we want to see if the string someString starts with the string “This”, then we can use the startsWith() method to let us know.

var someString = "This is some example text";

console.log(someString.startsWith("This"));

#Output
true

The startsWith method is case-sensitive, so note that if we tried entering in “this” in lowercase, we would get a different result.

var someString = "This is some example text";

console.log(someString.startsWith("this"));

#Output
false

Check if a String Ends with a Certain Character or String

To check if a String ends with a different string, we can use the endsWith() method. This works the same way as the startsWith() method but just checks at the end of the string, not the start.

someString.endsWith("anotherString");

Similarly as we did above, if we want to check if the string someString ends with the string “text”, then we can use the endsWith() method to let us know.

var someString = "This is some example text";

console.log(someString.endsWith("text"));

#Output
true

The endsWith method is also case-sensitive.

Hopefully this article has been useful for you to learn how to use the JavaScript String startsWith method.

Categorized in:

JavaScript,

Last Update: March 11, 2024