Confirm the Ending of a String: why was this wrong?

I just worked through the excercise “Confirm the Ending of the String” and my final solution was basically to compare a substring to the target:
` var string = str.substring(str.length -target.length);
if(string == target) {``
Like that. But I’m wondering my other two, original ideas didn’t work, specificially they worked on every test except:
confirmEnding(“Walking on water and developing software from a specification are easy if both are frozen”, “specification”) should return false.

` var check = str.split("");
 var length = check.length-1;
 var targetSplit = target.split("");
var targetLength = targetSplit.length-1;
var checkLength = length-targetLength;

if(check[length] == targetSplit[targetLength]) {
  return true;
} else {
return false;
}    

When that didn’t work I thought perhaps I needed to reverse and have a loop iterate through each letter at the end of the string going backwards:

 var reverseStr = str.split("").reverse();
 var reverseTarget = target.split("").reverse();
 var yes = true;
 for(var i = 0; i < reverseTarget.length; i++) {
 if(reverseStr[i] == reverseTarget[i]) {
  console.log(reverseStr + " and " + reverseTarget);
  return true;
} else
  return false;
}

}

I figured it out so it’s sort of moot but I want to know why neither of the above solutions work, specifically with that one question.

I think you need to review how to properly use the split function and its separator. You are using it with an undefined separator, which will give you an array element of size 1. Also, why would you want to split the target? I’m not familiar with JS, but I wonder if you can just use the target to return its index position within the array created by the split of the source.

split("") should be split(" “)
source.split(” ").indexOf(target)

Use console.log to see what is being generated after each step. Let me know what you find. I am interested!

1 Like

@tfantina your first attemp is checking one element in an array of letters against another letter in a different array. This attempt didn’t work because it doesn’t compare one string to another.

check is an array of letters. check[length] is one element in that array.

length is an integer that is equal to the number of elements in check minus one.

Not sure why you created checkLength since you don’t actually call afterward.

1 Like

Oh, ok I undestand. Thanks for your help. It makes total sense to me now why everything would work except for “frozen” and “specification” they both end in “n” but are not the same word so I was returning true because it was only checking the last letter in the array.

Thank you.

1 Like