I have Strangest bug in my code for subLength js problem, it's really weird

So this is the challenge…

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.


subLength('Saturday', 'a'); // returns 6
subLength('summer', 'm'); // returns 2
subLength('digitize', 'i'); // returns 0
subLength('cheesecake', 'k'); // returns 0

Here’s my code which ‘works’ but not if the searched character is capitalized.

function subLength(str, char) {
  let low = str.toLowerCase();
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] == char) {
  if (count !== 2) {
    return 0;
  let cut = low.split(char);
  let len = cut[1].length + 2;
  return len;

So console.log(subLength(“Saturday”, “a”)); gives 6
but console.log(subLength(“Anteater”, “a”)); gives 0

To find out what’s happening I returned low(variable) when I returned 0 and I returned cut(variable) at the end with len(the desired output). Some interesting stuff happens. Using ‘Saturday’ and variations of it with reordered letters and capitalization, I got these…

console.log(subLength(“Saturday”, “a”)); gives 6 and ‘s, turd, y’
console.log(subLength(“Aturday”, “a”)); gives 0 and ‘aturday’
console.log(subLength(“sAturday”, “a”)); gives 0 and ‘saturday’

After a good while thinking that toLowerCase had something against the letter A (I even test every letter in the alphabet :crazy_face:) I have come to the conclusion that toLowerCase is working on the strings as shown in the output, BUT I think it is working AFTER the count, so the count only sees one ‘a’ and so doesn’t move on to the split part of the function, but the toLowerCase does still execute.
I made a codepen of it as well if anyone wants to have a look


I’m actually quite pleased I got as far as finding out what is going wrong, but I a stumped about how I fix it. Would really appreciate any pointers.


Why aren’t you using the lower case string for the comparison?

1 Like

Thank God, I was going mad. In a way I think I learned more from this than I have any of the excercises so far, I’ve never drilled down into what’s happening to this extent before. Of course it ends up being something very simple in the end, I’m trying not to feel too foolish :grimacing:

Thankyou very much mirja.

(edit, just ran the code again and it works now)

1 Like

hey there, could you explain the logic behind this line, specifically why you’re referencing cut[1]? in the example of console.log(subLength(“Aturday”, “a”)), I would think that the split method would remove the first “a” from the returned array, and therefore cut[1] === ‘y’ (not ‘turd’). I must be missing something!