Javascript 如何检查字符串是否至少包含2个字母
我需要检查Javascript 如何检查字符串是否至少包含2个字母,javascript,Javascript,我需要检查test是否包含至少2个字母,如SC var test='SC129h'; if (test.containsalphabets atleast 2) { alert('success'); } else { alert('condition not satisfied for alphabets'); } 您应该使用正则表达式模式: /([A-Za-z])/g 并检查测试的长度是否大于2 var test = 'SC129h'; var match = test.matc
test
是否包含至少2个字母,如SC
var test='SC129h';
if (test.containsalphabets atleast 2) {
alert('success');
}
else {
alert('condition not satisfied for alphabets');
}
您应该使用正则表达式模式:
/([A-Za-z])/g
并检查测试的长度是否大于2
var test = 'SC129h';
var match = test.match(/([A-Za-z])/g);
if (match && match.length >= 2) {
alert('success');
}
else {
alert('condition not satisfied for alphabets');
}
更好的版本
var test = 'SC129h';
var match = test.match(/([A-Za-z])/g);
if (match && match[1]) {
alert('success');
}
else {
alert('condition not satisfied for alphabets');
}
创建正则表达式以匹配字母表中字符串中的所有字符,并对它们进行计数
var test = "SC129h";
if((test.match(/[A-Za-z]/g).length || 0) >= 2) {
alert("success");
}
或者,为了提高效率,进行线性搜索并检查ASCII代码。这样可以避免扫描整个字符串
var test = "SC129h";
var matches = 0;
for(var i = 0; i < test.length; i++) {
if((test[i] >= 'a' && test[i] <= 'z') || (test[i] >= 'A' && test[i] <= 'Z')) {
matches++;
if(matches > 2) break;
}
}
if(matches >= 2) {
// Do something here
}
var test=“SC129h”;
var匹配=0;
对于(变量i=0;i='a'和测试[i]='a'和测试[i]2)中断;
}
}
如果(匹配项>=2){
//在这里做点什么
}
您还可以删除所有非字母字符,然后检查结果的长度
'SC129h'.replace(/[^a-z]/gi,'').length > 1
您可以使用var match=/[a-z]{2,}/gi.test(test)
返回一个布尔值如果(test.length>=2)
请添加一些示例必须澄清,您有一个字符串'SC129h'
,您想检查它是否包含两个字母吗?如果(str.split(/[a-z]/).length-1)…
字母必须相邻吗?关于S6C
,这有效吗?.match()
有时返回null
,它没有长度。