Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/472.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何检查字符串是否至少包含2个字母_Javascript - Fatal编程技术网

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
,它没有长度。