subLength( ) coding challenge help

I’m doing the intermediate JavaScript coding challenges for Arrays, Loops, Objects, Iterators.
The challenge is to

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.

My solution (as strange as it might be) is nothing like the actual solution however seems to work. Here’s my solution.

function subLength(str, char){ let subStrArrLength = str.split(char).length; let subStrLength = str.split(char)[1].length + 2; if(subStrArrLength < 3 || subStrArrLength > 3){ return 0; } return subStrLength; } //these are the test examples console.log(subLength('Saturday', 'a')) console.log(subLength('summer', 'm')) console.log(subLength('digitize', 'i')) console.log(subLength('cheesecake', 'k'))

I would much appreciate any help with figuring out where I’m going wrong.

Why do you think you’re going wrong? Are the tests failing?

The tests are giving me the expected answers however when I click ‘Check Answer’ it doesnt confirm that it’s correct like the other questions. So I’m assuming that my solution is in some way wrong that I cant figure out.

Do you have a link to the page?

Link to Questions

let subStrLength = str.split(char)[1].length + 2;

If you run your code with a character that does not appear in the word at all, you get a type error, because


is undefined.

Like this, for example:

console.log(subLength('cheesecake', 'z'));
1 Like

Ahhhhhh ok! That’s it so. I fixed that there. Thankfully I didnt need to redo everything. Thank you very much for your help.

1 Like