Test If Input Values Match Constant Value
Ive got an assignment and am a bit stuck. Need to match an input string to the values in a constant, but I am matching individual characters. My constant would be ALPHABET = 'ABCDE
Solution 1:
Here's a single line answer to your question:
(ALPHABET.match(new RegExp((input.split('').join('|')), 'g'))).length == input.length
which would return true
only if all the characters in input
are present in ALPHABET
Here's a working demo http://jsfiddle.net/kayen/akL4A/
Solution 2:
One way is to loop over the input and search if it exits in the constant
Possible code
var ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUWXYZ';
var input = 'ABOZ'var count = 0;
for(x in input) {
if(ALPHABET.indexOf(input[x])>-1){
count++;
continue;
}
else{
break;
}
}
if(count==input.length) {
alert("true");
}
Solution 3:
Tested and works in Firefox 16. Remember this implementation does not verify if input is null or other defensive checks. You should do it by yourself. This is a case sensitive result.
Case insensitive :
functionvalidInput(input) {
varALPHABET = "ABCDEFGHIJKLMNOPQRSTUWXYZ";
for (var i = 0; i < input.length; i++) {
var charAtI = input.charAt(i);
var indexOfCharAtI = ALPHABET.indexOf(charAtI);
if (indexOfCharAtI < 0) {
returnfalse;
}
}
returntrue;
}
Case insensitive :
functionvalidInput(input) {
varALPHABET = "ABCDEFGHIJKLMNOPQRSTUWXYZ";
for (var i = 0; i < input.length; i++) {
var charAtI = input.charAt(i);
charAtI = charAtI.toUpperCase();
var indexOfCharAtI = ALPHABET.indexOf(charAtI);
if (indexOfCharAtI < 0) {
returnfalse;
}
}
returntrue;
}
Solution 4:
Here's an example of a function which would return true for a match or false for a mismatch. (Please note this is a case sensitive test).
varALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var input = 'ABOZ';
functiontestStr(str, constant){
var matchFlag = true;
var strSplit = str.split("");
for(var i=0; i<strSplit.length;i++){
if(constant.indexOf(strSplit[i]) == -1){
matchFlag = false;
}
}
return matchFlag;
}
alert(testStr(input, ALPHABET)); //TRUE
Post a Comment for "Test If Input Values Match Constant Value"