Hey, I was on the practice JavaScript, arrays, loops, objects, and iterators, and I ran into this exercise that’s got me stuck. The instructions are:
Write a function subLength()
that takes 2 parameters, a string and a single character. The function should search the string for the two occurrences of the character and return the length between them including the 2 characters. If there are less than 2 or more than 2 occurrences of the character the function should return 0.
Examples:
subLength(‘Saturday’, ‘a’); // returns 6
subLength(‘summer’, ‘m’); // returns 2
subLength(‘digitize’, ‘i’); // returns 0
subLength(‘cheesecake’, ‘k’); // returns 0
Here’s my code:
const subLength = (word, character) => {
let counter = 0;
let charcount = 0;
for (let i = 0; i < word.length; i++){
if (word[i] === character){
counter++;
while (word[i] != character){
charcount++;
}
}
}
if (counter > 2 || counter < 2){
return 0;
}else{
return charcount;
}
}
console.log(subLength('computation', 'o'));
All I’ve been getting are 0’s all day.
Thanks!