ES6 – Check if a string begins with other characters

Hi, in this post I’m going to show you how to check if a main string start with an other given string.

ES6 have a new method called startsWith() that will help us with that and this going to return us true or false.

const myString = "Cristina Elizabeth Rojas Zamora";

console.log(myString.startsWith("Cris"));

Result:

Upper or lower case does it matter? the answer is yes, if you try to find “cris” (lower case) then we will have false.

const myString = "Cristina Elizabeth Rojas Zamora";

console.log(myString.startsWith("cris"));

Result:

Nice, now if we want to start searching from specific character then we can insert a second parameter in .startsWith( ) method

const myString = "Cristina Elizabeth Rojas Zamora";

console.log(myString.startsWith("liza", 10));

Result:

This is because the main string start from 0 and continue, then we define the specific position in .startsWith( ) method and this method will start searching in that position.

Note: if you have myString.startsWith(“liza”, 9),   myString.startsWith(“liza”, 11) this will be false.

If you want to check if a string ends with some other string then used this method:

endsWith(string, index).

By Cristina Rojas.