How to check if first character in string is a letter in JavaScript

How to check if first character in string is a letter in JavaScript

Posted by Ervin Adams on July 19, 2022

How to check if first character in string is a letter in JavaScript

How to check if first character in string is a letter in JavaScript

Posted by Ervin Adams on July 19, 2022

There is a few ways to check if the first character in a string is a letter in JavaScript. Let us go through a few.

Firstly, you have to isolate the first character in the string:

let char = str.charAt(0)

Now you can check the character by using the JavaScript test() method with Regex:

function checkChar(char){
  return return /^[a-z]/i.test(char);
}

If the first character is a letter it will return true, otherwise it will return false.

Regex examples:

let str = "Dentry Drive";
let str1 = "16 Dentry Drive";

let char = str.charAt(0);
let char1 = str1.charAt(0);

function checkChar(char){
  return /^[a-z]/i.test(char);
}

console.log(checkChar(char)); //true
console.log(checkChar(char1)); //false

Or you can use the isNaN() JavaScript method.

IsNaN examples:

let str = "Dentry Drive";
let str1 = "16 Dentry Drive";

let char = str.charAt(0);
let char1 = str1.charAt(0);

console.log(isNaN(char)); //true
console.log(isNaN(char1)); //false

Or you can parse the character using parseInt() method with the Number.isInteger() method. These are JavaScipt built in resources, so no need for third party packages or plugins.

Parsing examples:

let str = "Dentry Drive";
let str1 = "16 Dentry Drive";

let char = str.charAt(0);
let char1 = str1.charAt(0);

console.log(Number.isInteger(parseInt(char))); //false
console.log(Number.isInteger(parseInt(char1))); //true

Notice the different with parsing that the results are switched around.