如何检查字符串是否包含至少2个字母

时间:2016-04-01 06:43:45

标签: javascript

我需要检查test是否包含至少2个字母,例如SC

var test='SC129h';
if (test.containsalphabets atleast 2) {
  alert('success');
}
else {
  alert('condition not satisfied for alphabets');
}

4 个答案:

答案 0 :(得分:3)

您应该使用RegEx模式:

/([A-Za-z])/g

并检查test的长度是否超过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');
}

答案 1 :(得分:1)

创建一个正则表达式,以匹配字母表中字符串中的所有字符,并计算它们。

V get(Object key, int hash) { 
  if (count != 0) { // read-volatile 
    HashEntry<K,V> e = getFirst(hash); 
    while (e != null) { 
      if (e.hash == hash && key.equals(e.key)) { 
        V v = e.value; 
        if (v != null) 
          return v; 
        return readValueUnderLock(e); // recheck 
      } 
      e = e.next; 
    } 
  } 
  return null; 
}

或者,为了提高效率,请进行线性搜索并检查ASCII码。这可以避免扫描整个字符串。

var test = "SC129h";
if((test.match(/[A-Za-z]/g).length || 0) >= 2) {
    alert("success");
}

答案 2 :(得分:0)

您还可以删除所有非字母字符,然后检查结果的长度。

'SC129h'.replace(/[^a-z]/gi,'').length > 1

答案 3 :(得分:0)

你可以var match = /[a-z]{2,}/gi.test(test)使用返回布尔值

相关问题