I’ve been trying to complete the exercise to calculate subLength() in the “JavaScript Practice: Arrays, Loops, Objects, Iterators” exercise in the full stack developer course found here:
Here’s my code:
// Write function below
const subLength = (string, character) => {
str = string
cha = character
const checkOccurences = (str, cha) => {
let count = 0
let position = string.indexOf(cha)
while (position !== -1) {
count++
position = string.indexOf(cha, position + 1)
}
return count
};
if (checkOccurences < 2 || checkOccurences > 2) {
return 0
} else {
let firstOcc = string.indexOf(character)
let lastOcc = string.lastIndexOf(character)
let midSection = string.substr(firstOcc, lastOcc)
return midSection.length
}
}
But it’s not working - I’m receiving output, but the numbers seem unrelated to the values that were passed in (e.g. console.log(subLength(‘digitize’, ‘i’)) is giving an output of 5).
Can anyone help me, please?