Check if input is a letter

Check if input is a letter

As a blogger, I have come across a lot of instances where I needed to check if a user input is a letter or not. The following are some ways you can achieve this in HTML:

Using Regular Expression

You can use regular expressions to check if the input is a letter or not. You can define a regular expression pattern which checks for any character from A to Z, both uppercase and lowercase.


      function isLetter(input) {
        const pattern = /^[a-zA-Z]+$/;
        return pattern.test(input);
      }
    

The above code defines a function called isLetter which takes an input parameter and returns true if the input consists of only letters and false otherwise. The regular expression pattern /^[a-zA-Z]+$/ checks if the input contains only uppercase or lowercase letters.

Using ASCII values

You can also use the ASCII values of the characters to check if the input is a letter or not. Every character in JavaScript has an associated ASCII value. Uppercase letters start from 65 and end at 90, while lowercase letters start from 97 and end at 122. Any character outside this range is not a letter.


      function isLetter(input) {
        const code = input.charCodeAt(0);
        return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
      }
    

The above code defines a function called isLetter which takes an input parameter and returns true if the input consists of only letters and false otherwise. The charCodeAt() method is used to get the ASCII value of the first character in the input string.

Using isNaN() function

You can also use the isNaN() function to check if the input is a letter or not. The isNaN() function returns true if the input is not a number, and false otherwise. Since letters are not numbers, this function can be used to check if the input is a letter or not.


      function isLetter(input) {
        return isNaN(input);
      }
    

The above code defines a function called isLetter which takes an input parameter and returns true if the input consists of only letters and false otherwise. The isNaN() function is used to check if the input is a number or not. Since letters are not numbers, this function can be used to check if the input is a letter or not.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe