Bry*_*ahn 5 javascript regex string input
我有一个字段,您可以在其中输入您的姓名并提交。我希望接收人的名字和姓氏,为此,我需要检查值是否至少包含2个字。这就是我现在正在使用的东西,但是似乎没有用。
function validateNameNumber(name) {
var NAME = name.value;
var matches = NAME.match(/\b[^\d\s]+\b/g);
if (matches && matches.length >= 2) {
//two or more words
return true;
} else {
//not enough words
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
sim*_*rry 10
str.trim().indexOf(' ') != -1 //there is at least one space, excluding leading and training spaces
Run Code Online (Sandbox Code Playgroud)
您可以使用 String.Split() 方法:
function validateNameNumber(name) {
var NAME = name.value;
var values = name.split(' ').filter(function(v){return v!==''});
if (values.length > 1) {
//two or more words
return true;
} else {
//not enough words
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您要传递“John Doe”作为名称值,则值将等于 {"john", "doe"}
http://www.w3schools.com/jsref/jsref_split.asp
编辑:添加过滤器以删除空值。来源:从字符串数组中删除空字符串 - JQuery
归档时间: |
|
查看次数: |
7176 次 |
最近记录: |