检查字符串是否仅包含javascript中的字母 [英] Check if string contains only letters in javascript
本文介绍了检查字符串是否仅包含javascript中的字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我尝试了这个:
if (/^[a-zA-Z]/.test(word)) {
// code
}
它不接受这个:
但它接受这个:word word
,它确实包含一个空格:/
But it does accept this: "word word"
, which does contain a space :/
有没有一个好办法呢?
推荐答案
使用 / ^ [a-zA-Z] /
只检查第一个字符:
With /^[a-zA-Z]/
you only check the first character:
-
^
:断言字符串开头的位置 -
[a-zA-Z]
:匹配下面列表中的单个字符:
-
az
:a和z之间的字符 -
AZ
:A A和Z之间的字符
^
: Assert position at the beginning of the string[a-zA-Z]
: Match a single character present in the list below:a-z
: A character in the range between "a" and "z"A-Z
: A character in the range between "A" and "Z"
如果你想要要检查所有字符是否都是字母,请改用:
If you want to check if all characters are letters, use this instead:
/^[a-zA-Z]+$/.test(str);
-
^
:断言字符串开头的位置 -
[a-zA-Z]
:匹配下面列表中的单个字符:
-
+
:在一次和无限次之间,尽可能多,根据需要回馈(贪心) -
az
:a和z之间的字符 -
AZ
:A和Z之间的字符 ^
: Assert position at the beginning of the string[a-zA-Z]
: Match a single character present in the list below:+
: Between one and unlimited times, as many as possible, giving back as needed (greedy)a-z
: A character in the range between "a" and "z"A-Z
: A character in the range between "A" and "Z"
或者,使用不区分大小写的标志
i
,您可以将其简化为Or, using the case-insensitive flag
i
, you could simplify it to/^[a-z]+$/i.test(str);
或者,因为你只想
测试
,而不是匹配
,你可以检查相反的情况,并否定它:Or, since you only want to
test
, and notmatch
, you could check for the opposite, and negate it:!/[^a-z]/i.test(str);
这篇关于检查字符串是否仅包含javascript中的字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-
-
查看全文