Solution suggestion for Confirm the Ending lesson in basic algorithm scripting

This lesson is clear. However, string.substr(start, length) is not mentioned anywhere.
Since the instruction asks for javaScript substring methods , this solution and explanation may add a point to the lesson.

This is pretty much identical to str.slice( ) method.

Summary

The function gets one string- str and compares the second argument-target with the ending of the first string-str.
The str.substring method, in this case, must be called in order to separate a substring based on the second argument-target.
To extract the last characters, the input must be negative.
Here we use target.length to precisely separate the number of letters from the ending of str based on the target’s length.
If the actual value of target is equal to this substring then the input is confirmed.

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

confirmEnding("Bastian", "ian");
  • String.prototype.substring(indexStart, indexEnd) method extracts part of a string.

  • The start is negative, substr( ) uses it as a character index from the end of the string.

I recommend against inclusion of this solution:

Furthermore, substr() is considered a legacy feature in ECMAScript and could be removed from future versions, so it is best to avoid using it if possible.

1 Like