Hi Friends 👋,

Welcome To Infinitbility! ❤️

Today, I’m going to show How do check if the first character of a string is a letter in Javascript, here I will use the javascript string charAt() method and regex expression to check if the first character of a string is an alphabet or not.

What is a charAt() method?

The String object’s charAt() method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string.

Let’s start the today’s tutorial How do you check if the first character of a string is a number in JavaScript?

Let’s understand how we can do it

  1. Take sample string variable examples
  2. Use the charAt() method with index 0 to get first character
  3. Use the regex expression and console whether it’s a letter or not
// string regex format
const strFormat = /[a-z]/i;

// Take sample string variable examples
const str1 = 'Hello world';
const str2 = '8ly';

// Use the `charAt()` method with index 0 to get first character
// Use the regex expression and console whether it's a letter or not

// valid case example
if (strFormat.test(str1.charAt(0))) {
    console.log("First character is a letter");
} else {
    console.log("First character isn't a letter");
}

// invalid case example
if (strFormat.test(str2.charAt(0))) {
    console.log("First character is a letter");
} else {
    console.log("First character isn't a letter");
}

The above program is the simplest way to check the string first character of a letter or not. let’s check the output.

javascript, check if the first character of a string is a letter example
javascript, check if the first character of a string is a letter example

I hope it’s help you, All the best 👍.