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');
}
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');
}
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');
}
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
}
You can also remove all non alphabetic characters then checking for the length of the result.
'SC129h'.replace(/[^a-z]/gi,'').length > 1