Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

Today, I’m going to show How do I check if the first character of a string is a number in Javascript, here I will use the javascript string charAt(), and isNaN() method to check if the first character of a string is a number 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.

What is a isNaN() method?

The isNaN() function determines whether a value is NaN or not. Because coercion inside the isNaN function can be surprising, you may alternatively want to use Number.isNaN().

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
  2. Use the charAt() method with index 0 to get first character
  3. Use the isNaN() method and console whether it’s a number or not
// Take sample string variable
const str1 = 'Hello world';
const str2 = '8ly';

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

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

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

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

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

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