Confirm the Ending - Need a little help?

function confirmEnding(str, target) {

var ending = str.substr(str.length-1, target.length);

if(ending === target){
return true;
}
else{
return false;
}

}

I’m not sure why this isn’t hitting all of the tests right. Thoughts?

function confirmEnding(str, target) {

var ending = str.substr(str.length-target.length);
. console.log("ending: " + ending + ", target: " + target);
if(ending === target){
. return true;
}
else{
. return false;
}
}

Hi. Take a look at the console log line that I put in to be able to see that your variable ‘ending’ wasn’t doing what you expected it to.

I think if you change it like I did here it will work (you were very close!) but I didn’t test it.

1 Like

Thanks for the correction!

I’m still conceptually trying to wrap my head around why str.substr(str.length-1, target.length) is different than str.substr(str.length-target.length).

I get what str.substr(str.length-target.length) is trying to accomplish (subtract the number of characters in “target” from the end of str.

Is the way I had it (str.substr(str.length-1, target.length)) just telling it to subtract the number of characters…but it wasn’t taking it from the end of the string?

(str.substr(str.length-1, target.length))

The first argument tells it where to start chopping out - the second one, if it’s there tells it how many elements to take. You had it starting at str.length-1 which will be the penultimate element. You want it to start ‘target.length’ back from the end of the string and chop out to the end (so you don’t need a second argument)

It often helps to carefully read the docs for the APIs that you’re using. Take a look substr API

str.substr(start , length)

First argument is start - Meaning the index from which you want to extract the part of the string.
What you’ve specified is str.length-1. Which means, you want to start from last character.

This is fine if and only if your target is of length 1.

But there are many test cases where your target.length is > 1

So what you need to do is, you need to specify start as (str.length - target.length) which means, you will start extracting characters.

2nd argument is optional. In this context, it is not even required. If 2nd argument is absent, substr will extract all characters from start index to end of the string.

So your updated code should look like

function confirmEnding(str, target) {

var ending = str.substr(str.length - target.length);

  if(ending === target){
    return true;
  } else{
    return false;
  }
}

confirmEnding("Bastian", "n");

Additionally, the substr docs also mention that if your specify start as a negative value, it will give you that many characters from the end of string. You can use this like

function confirmEnding(str, target) {
  return str.substr(-target.length) == target;
}