How to check if character is a letter in Javascript?

前端 未结 13 1768
渐次进展
渐次进展 2020-11-27 14:38

I am extracting a character in a Javascript string with:

var first = str.charAt(0);

and I would like to check whether it is a letter. Stran

13条回答
  •  独厮守ぢ
    2020-11-27 15:31

    I`m posting here because I didn't want to post a new question. Assuming there aren't any single character declarations in the code, you can eval() the character to cause an error and check the type of the character. Something like:

    function testForLetter(character) {
      try {
        //Variable declarations can't start with digits or operators
        //If no error is thrown check for dollar or underscore. Those are the only nonletter characters that are allowed as identifiers
        eval("let " + character + ";");
        let regExSpecial = /[^\$_]/;
        return regExSpecial.test(character);
      } catch (error) {
        return false;
      }
    }
    
    console.log(testForLetter("!")); //returns false;
    console.log(testForLetter("5")); //returns false;
    console.log(testForLetter("ن")); //returns true;
    console.log(testForLetter("_")); //returns false;

提交回复
热议问题