Javascript正则表达式应该允许空和非空字符串,但它不会
I've a regular expression that allows a string to be empty. If it isn't empty the string may contain only letters and spaces. But it may not start or end with a space.
我有一个正则表达式,允许字符串为空。如果它不为空,则字符串可能只包含字母和空格。但它可能无法以空间开始或结束。
This RegExp should do this job: ^(?! )[a-zA-Z]*[a-zA-Z ]*$
I've tested it here: http://tools.netshiftmedia.com/regexlibrary/
这个RegExp应该做这个工作:^(?!)[a-zA-Z] * [a-zA-Z] * $我在这里测试过:http://tools.netshiftmedia.com/regexlibrary/
But when I'm implementing this in my js, it doesn't allow a string to be empty.
但是当我在我的js中实现它时,它不允许字符串为空。
This is the code
这是代码
function validatePreposition(name) {
string = string = document.forms['form'][name].value;
pattern = new RegExp('^(?! )[a-zA-Z]*[a-zA-Z ]*$');
checkString(name, pattern, string);
}
function checkString(name, pattern, string) {
if(!pattern.test(string)) {
error[name] = 1;
} else {
error[name] = 0;
}
printErrors();
}
How change my code so that an empty string is allowed?
如何更改我的代码以便允许空字符串?
2 个解决方案
#1
14
Try using this instead:
请尝试使用此代码:
pattern = /(^[a-zA-Z]+(\s*[a-zA-Z]+)*$)|(^$)/;
It will either test for an empty string or test for a string that starts with a a-Z and may have unlimited amount of spaces in the string but have to end with a-Z.
它将测试空字符串或测试以a-Z开头的字符串,并且可能在字符串中具有无限量的空格但必须以a-Z结尾。
You can see it in action here: http://jsfiddle.net/BAXya/
你可以在这里看到它:http://jsfiddle.net/BAXya/
更多相关文章
- 获取拆分字符串数组的最后一个元素
- 常用验证JS代码基础及实例
- “错误:路径必须是字符串”(v5.10.0)
- javascript 截取字符串方法汇总
- JavaScript String(字符串对象)
- JS将字符串转换为数组
- 在变量名是字符串时声明变量?
- 试着在我的javascript代码中理解“this”(一件事有效,另一件没有)
- 可编辑div中的文本计数和子字符串