How to check if character is a letter in Javascript?

前端 未结 13 1872
渐次进展
渐次进展 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:37

    ES6 supports unicode-aware regular expressions.

    RegExp(/^\p{L}/,'u').test(str)
    

    This works for all alphabets.

    Unfortunately, there is a bug in Firefox (will be fixed in version 78) that prevents this from being used universally. But if you can control your runtime environment and it supports it (e.g. Node.js), this is a straightforward, comprehensive solution.

    Atlernatively, XRegExp provides a polyfill of modern regular expression to all browsers.

提交回复
热议问题