Need help with coding question in Javascript Syntax

Hi everyone, I’m stuck at the answer to this question:

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

And here is my answer:

// Write function below
// Write function below
const subLength = (str,char) => {
  let totalChar = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] === char) {
      totalChar++;
    }
  }
  if (totalChar < 2 || totalChar > 2) {
    return console.log(0);
  } else {

  let strLength = str.length;
  let char1 = str.indexOf(char);
  let char2 = str.lastIndexOf(char);
  let result = strLength - char1 - (strLength - char2) + 1;
  console.log(result);
  
  }
};

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


I did run the test and check the answer and it told me I was wrong, but I tested the case and it returns exactly the expected answer. Is there anything that I missed here?

According to the text posted by you, the instructions specify

“…return the length between them including the 2 characters… the function should return 0.”

Instead of return 0; , you have: return console.log(0);

Instead of return result; , you have console.log(result);

The feedback is correct that your code didn’t return 2.

1 Like

Thanks! It works now.

1 Like