I am trying to solve the following issue:
Find the missing letter in the passed letter range and return it. If all letters are present in the range, return undefine
This is an even shorter answer thanks to RegExp()
that allows you to create a Regular Expression on the fly and use match()
to strip off the given letters from a generated String that has all the letters in the given range:
function fearNotLetter(str) {
var allChars = '';
var notChars = new RegExp('[^'+str+']','g');
for (var i=0;allChars[allChars.length-1] !== str[str.length-1] ;i++)
allChars += String.fromCharCode(str[0].charCodeAt(0)+i);
return allChars.match(notChars) ? allChars.match(notChars).join('') : undefined;
}
Here's my another answer in missing letters:
function fearNotLetter(str) {
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
var first = alphabet.indexOf(str[0]);
var last = alphabet.indexOf(str[str.length-1]);
var alpha = alphabet.slice(first,last);
for(var i=0;i<str.length;i++){
if(str[i] !== alpha[i]){
return alpha[i];
}
}
}
console.log(fearNotLetter("abce"));
I think that you wanted to say that if a string doesn't start with "a" than return "undefined". So here's my code:
function fearNotLetter(str) {
var alphabet = ("abcdefgheijklmnopqrstuvwxyz");
var i = 0;
var j = 0;
while (i < alphabet.length && j < str.length) {
if (alphabet.charAt(i) != str.charAt(j)) {
i++;
j++;
if (alphabet.charAt(i - 1) == "a") {
return "undefined";
} else {
return (alphabet.charAt(i - 1));
}
}
i++;
j++;
}
}
alert(fearNotLetter('abce'));
Here's the working JsFiddle.
You wanted the code to return the missing letter so I used CharAt.
You can make an array of letters and then search through it to see if it maches with letters from the string....
Another function that may help:
var alphabet = "abcdefgheijklmnopqrstuvwxyz";
function fearNotLetter(a) {
function letterIndex(text, index) {
var letter = text.charAt(0);
if (alphabet.indexOf(letter) !== index) { return alphabet.charAt(index); } else { return letterIndex(text.substring(1), index + 1) }
}
if (alphabet.indexOf(a) === -1) {
return letterIndex(a, alphabet.indexOf(a.charAt(0)));
}
return undefined;
}
fearNotLetter("abc"); //Undefined
fearNotLetter("abce"); //d
fearNotLetter("fgi"); //h