Hi all! I’m new at coding and I have encountered a code challenge that I can’t solve. My code is returning the “correct” values as far as I can tell, but it is not passing the exercise. Any help would be highly appreciated.
My code is pasted below:
let counter=0;
let result=0;
const subLength = (str,char) => {
// split into string array
stringArray=str.toLowerCase().split('');
// count the repetitions
stringArray.forEach(item => {
if (item === char){
counter++;
}
})
// evaluate if num of reps is 2
if (counter === 2) {
result = stringArray.lastIndexOf(char)-stringArray.indexOf(char)+1
}
// set result to 0 if not right amount of reps
else if (counter != 2){
result = 0;
}
return result;
}
When I test my code using console.log(subLength(‘funny’,‘n’)) it prints 2 to the console. However, when I click ‘check answer’ it gives me the error Tested subLength('funny', 'n')
and it did not return 2
. Can you help me understand what went wrong in my code?