I am using regex to verify that a string only contains alphabets and spaces. Regex is defined as
var regex = /^[A-Za-z ]/;
but even if I am testing it with a string "X," , it is giving a true result.
What is the error here?
I am using regex to verify that a string only contains alphabets and spaces. Regex is defined as
var regex = /^[A-Za-z ]/;
but even if I am testing it with a string "X," , it is giving a true result.
What is the error here?
^[A-Za-z ]
只匹配一个字符。并且^
表示字符串的开头。要完成您想要的,请使用:
+
- 这意味着匹配一个或多个。或者,您可以使用:
*
- 这意味着匹配零个或多个。
但我认为你最好用第一个(+
)。另一件事是,匹配整个字符串。这意味着您必须从第一个字符搜索到最后一个字符。
$
- 这意味着匹配结束。
你的代码应该是这样的:
var regex = /^[A-Za-z ]+$/;
您的正则表达式匹配您输入的第一个字母,因此返回 true。您需要添加$
以确保仅匹配从开头 ( ^
) 到结尾 ( $
) 的完整字符串。
var regex = /^[A-Za-z ]*$/;
尝试使用这个:
/^[a-zA-Z\ ]+$/