In this article, you’ll learn how to check if a string starts with a specific string or a character in javascript. You can easily achieve either through the startsWith()
method, or regular expressions.
In this example, we used the javascript built-in function startsWith()
to check if a string starts with a specific string or a character or not. The startsWith()
method determines whether a String Starts with a Specific String or a Character. This method returns true
if the string begins with a specific string or a character, and false
if not.
//Example 1
const str = "Tutorialsrack";
console.log(str.startsWith("T")); // true
console.log(str.startsWith("i")); // false
//Example 2
const str1 = "This is an example of startsWith() method";
console.log(str1.startsWith("This")); // true
console.log(str1.startsWith("is", 2)); // true
In this example, we used the regular expression to check if a string starts with a specific string or a character or not. The regexObj.test(reg)
method used to match the specified regular expression reg
to the original string and returns a boolean
value which indicates if a match was found or not:
//Example 1
const str = "Tutorialsrack";
const regEx = /^Tut/;
console.log(regEx.test(str)); // true
//Example 2
const str1 = "This is an example for startsWith() method";
const regEx1 = /^This/;
console.log(regEx1.test(str1)); // true
I hope this article will help you to understand how to check if a string starts with a specific string or a character in javascript.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments