Confirm the Endings

Confirm the Endings
0

#1

** Hello guys, I have been battling with this challenge for whole day now. The two result below is not passing. please fellow campers what could possibly be wrong with my code.

confirmEnding(“Congratulation”, “on”) should return true:**
confirmEnding(“Open sesame”, “same”) should return true.

Your code so far


function confirmEnding(str, target) {
  // "Never give up and good luck will find you."
  var splitWord = str.split("");
  var splitWordNoQuote = str.split(" ");
  var targetWord = target.split(" ");
  var targetWordNoQuote = target.split(" ")
  
if (splitWord[splitWord.length-1] === targetWord[targetWord.length-1]) {
    return true;
  }
  else if (splitWordNoQuote[splitWordNoQuote.length-1] === targetWordNoQuote[targetWordNoQuote.length-1]) {
    return true; }
    else{
      return false;
    }
  

  // -- Falcor
  return str;
}

confirmEnding("Bastian", "n");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/confirm-the-ending


#2

You may be making it too hard for yourself. The exercise asks you to use one of the substring methods:

String.prototype.substring()

so you’d want to see if str ends with target. How would you use substring to extract the ending part of str to compare against the target?

Hope this helps…


#3

For the test case of confirmEnding(“Congratulation”, “on”), the above if statement is comparing “n” to “on”, so it does not evaluate to true.

For the test case of confirmEnding(“Congratulation”, “on”), the above else if statement is comparing “Congratulation” to “on”, so it does not evaluate to true.

Since both of these evaluate to false, your else returns false.


#4

Thanks guys, i guess i’m making the whole too hard for myself. let me try the substring method.


#5

yes!!!
my new code below passed the test. Thanks guys for pushing my brain to think.

function confirmEnding(str, target) {
// “Never give up and good luck will find you.”
let targetLength = target.length;
let strLength = str.length;
if (str.substr((strLength - targetLength), targetLength)=== target) {
return true;
} else {
return false;
}

// – Falcor
return str;
}


#6

FYI, because the === operator will evaluate to true or false, you do not need two separate return states. You can instead use a single return of the expression.

return str.substr((strLength - targetLength), targetLength)=== target

Also, your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution.