Confirm the Ending 0

Tell us what’s happening:
How does this code work?

Your code so far

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

confirmEnding("Bastian", "n");

Your browser information:

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

Link to the challenge:

That’s a really good question — wanting to understand how something works is awesome!


confirmEnding("Bastian", "n")

will just set str to “Bastian”, and target to “n” – within the function. Let’s replace every instance of str and target therefore.

return "Bastian".substr(-"n".length) === "n";

.substr() stands for “substring” and is designed to give you some shorter string that’s contained within the bigger string.

How does .substr() work? Well, it can accept up to two arguments (let’s call them s and l)

  • If s is positive, skip the first s characters
  • If s is negative, show the last s characters
  • If l is set, show a maximum of l characters

Here are some examples:

"abcde".substr(2) // "cde"
"abcde".substr(2, 1) // "c"
"abcde".substr(-1) // "e"
"abcde".substr(-2) // "de"
"abcde".substr(-2, 1) // "d"

So that’s cool.

return "Bastian".substr(-1) === "n";
// ...
return "n" === "n";

Yet if our second argument is longer, like “ian”, .substr(-3) will gives us the last three characters, allowing us to compare even longer endings.

Hope that clears stuff up?

You can look up a particular function by googling it. “string substr javascript mdn” would be some good keywords. :slightly_smiling_face: