;

How to Check if a String Starts With a Specific String or a Character in Javascript


Tutorialsrack 28/06/2021 Jquery Javascript

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.

Example 1: Check if String Starts with Specific String or a Character Using startsWith() Method

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: Check if String Starts with Specific String or a Character Using startsWith() Method
//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

Example 2: Check if String Starts with Specific String or a Character Using Regular Expressions

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 2: Check if String Starts with Specific String or a Character Using Regular Expressions
//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!


Related Posts



Comments

Recent Posts
Tags