Right and wrong way to "Confirm the Ending"

Apologize if this is in the wrong category. Was unsure if it fit under the help or javascript section. Appreciate anyone who replies.

The context:
So this is not so much a question for help as it is a question about function.
When finishing every task I usually take a look at the Get a Hint section to find out how the task was intended to be solved. The hint page says to use the str.slice() function, and my question is this:

  1. Are there any notible differences in efficiency between the slice() and substring() methods?
  2. Is there a right and wrong way to solve it?

My thought process and code is added below.

My code

function confirmEnding(str, target) {
  // since the target can be an arbritrary length we first need to find out how long the target is
  // then we need to find out how long the str is 
  // subtract the target length from the string length to find where the substring should start.
  // we must then compare the ending of the substring with the target and return true or false.

  return (str.substring((str.length-target.length)) === target);

confirmEnding("Bastian", "n");

Link to the challenge:
Confirm the Ending task
Hint Page for Confirm the Ending

First I think the slice use for array and substring method use for string. So you should be used substring.

  1. Base on syntax substring: str.substring(indexStart[, indexEnd]).

If you have a string is: var str = ‘Mozilla’ (Length of the string is 7);

  • str.substring(0,3) => Method 1 will get string form indexOf 0 to indexOf 3 => Result is ‘Moz’

  • str.substring(5) => Method 2 will get string form indexOf 5 to indexOf 7(str.length) => Result is ‘la’

So if you want to find the string end:

  1. You find length of the target.

  2. Base on length of target you can you method 2 to find the indexOf start by (str.length-target.length)

  3. You have the substring of string

  4. Compare with target.

var str = ‘Mozilla’
confirmEnding(“Mozilla”, “a”);
Length of string ‘Mozilla’ = 7 and length of ‘a’ = 1.
Next i want to get character end of the string with length = 1.
I get the character by str.substring(str.length - target.length) = str.substring(7 -1) = str.substring(6)
In the string get chracter from indexOf 6 -> end(indexOf7).
We has chracter a then we compare with target

Thank you for the reply
I understood how it works, I was just not sure when it was apropriate to use slice() or substring().
You solved that as well.:smiley:

1 Like