-1

I need to check if test contains at least 2 letters, like SC.

var test='SC129h';
if (test.containsalphabets atleast 2) {
  alert('success');
}
else {
  alert('condition not satisfied for alphabets');
}
Adrian Lynch
  • 8,237
  • 2
  • 32
  • 40
Sangeetha cg
  • 81
  • 5
  • 14

4 Answers4

3

You should be using the RegEx pattern:

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

And check for the length of the test to be more than 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');
}

Better Version

var test = 'SC129h';
var match = test.match(/([A-Za-z])/g);
if (match && match[1]) {
  alert('success');
}
else {
  alert('condition not satisfied for alphabets');
}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
3

Create a regular expression to match all characters in the string that are in the alphabet, and count them.

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

Alternatively, to be more efficient, do a linear search and check the ASCII code. This can avoid scanning the whole string.

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
}
Jamie
  • 1,096
  • 2
  • 19
  • 38
0

You can also remove all non alphabetic characters then checking for the length of the result.

'SC129h'.replace(/[^a-z]/gi,'').length > 1
Lewis
  • 14,132
  • 12
  • 66
  • 87
0

you could do var match = /[a-z]{2,}/gi.test(test) with would return a Boolean

echopeak
  • 251
  • 1
  • 2
  • 9