Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To check character is a letter or number, JavaScript provides the isNaN() method just pass your character as a parameter it will check character is NaN ( Not a number ) when it returns false means the character is a number else validate the character with regex code /^[a-zA-Z]+$/ to check is a letter or not.

Today, I’m going to show How do I check if a character is a letter or number in Javascript, here I will use the javascript string isNaN() method, and regex code /^[a-zA-Z]+$/` to check if a character is a letter or number.

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().

What is a regex code /^[a-zA-Z]+$/?

This regex code is a format of string letter, using this regex code we are able to validate character is a letter or not.

Let’s start the today’s tutorial How do you check if a character is a letter or number in JavaScript?

In the following example, we will check whether a character is a number or not using the isNaN() method when a character is a not a number we will use our regex code to check character is a letter or not.

// Example of character is a letter
const str1 = "infinitbility";

if(!isNaN(str1)){
  console.log('âś… character is a number')
} else if(/^[a-zA-Z]+$/.test(str1)) {
  console.log('âś… character is a letter')
}

// Example of character is a Number
const str2 = "903";

if(!isNaN(str2)){
  console.log('âś… character is a number')
} else if(/^[a-zA-Z]+$/.test(str2)) {
  console.log('âś… character is a letter')
}

In the above program, we take example of both if string is a letter or string is a number, let’s check the output.

javascript, check if a character is a letter or number example
javascript, check if a character is a letter or number example

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