Test if string contains only letters (a-z + é ü ö ê å ø etc..)

后端 未结 12 1328
不思量自难忘°
不思量自难忘° 2020-12-04 18:12

I want to match a string to make sure it contains only letters.

I\'ve got this and it works just fine:

var onlyLetters = /^[a-zA-Z]*$/.test(myString)         


        
12条回答
  •  鱼传尺愫
    2020-12-04 18:27

    You can't do this in JS. It has a very limited regex and normalizer support. You would need to construct a lengthy and unmaintainable character array with all possible latin characters with diacritical marks (I guess there are around 500 different ones). Rather delegate the validation task to the server side which uses another language with more regex capabilties, if necessary with help of ajax.

    In a full fledged regex environment you could just test if the string matches \p{L}+. Here's a Java example:

    boolean valid = string.matches("\\p{L}+");
    

    Alternatively, you could also normailze the text to get rid of the diacritical marks and check if it contains [A-Za-z]+ only. Here's again a Java example:

    string = Normalizer.normalize(string, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
    boolean valid = string.matches("[A-Za-z]+");
    

    PHP supports similar functions.

提交回复
热议问题