Confirm the Ending without endsWith()

Tell us what’s happening:
I am trying to see if the target parameter matches the end of the str parameter without using the endsWith() string method. I console.log() each line of code and everything seems to be called/accesses properly.

What would be wrong with my logic below? I am trying to compare the last X indexes in the str parameter. I would do that using .substring() and starting from ((str.length - 1) - (target.length - 1))

Your code so far


function confirmEnding(str, target) {
  // "Never give up and good luck will find you."
  // -- Falcor
  str.substring((str.length -1)-(target.length-1)) === target ? true : false; 
}
confirmEnding("Bastian", "n");

Link to the challenge:

Hey @cog3

Its is really good question that you brought up here. I checked your solution it works fine. You have to understand that substring is a function and when you return true or false. it is basically completing that function. Please remember you are not returning true/false for the confirmEnding function. You can easily do that by storing the return value of the substring function in a variable and return that variable.

Check the example below

Not necessary to assign the expression to a variable and return the variable. The OP just needed to add return in front of expression.

1 Like

Oh is it, Thanks for the info @RandellDawson ! . I will keep this in mind.

Every time I add the return keyword in my ternary operators, i get errors from the FCC compiler.

I would need to see the code you tried which results in errors.

Hi @cog3:

I find that you ternary operator needs “return” and that you should use substring lengths of target and str. Your ternary could work without errors as below:

 return str.substring(str.length-target.length,str.length)===target ? true : false; 

Keep in mind that you use -target.length instead of -1 since target is dynamic. substring() parameters can be in reverse order as long you pass one higher than the other, Javascript will understand that the lower value is the starting index and higher value the end.
Hope this helps

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

Thank you for understanding.