Check if a string ends with a given suffix, without using .endswith() I figured out how to do this assignment, but now that I have, I'd like to know if there is a cleaner way to do it. Below is what was required of the assignment, below that is my working function that got me the correct answer and further below that is the all the statements that it had to and did pass. 

How can I make it better?


  Check if a string (first argument, str) ends with the given target
  string (second argument, target).
  
  This challenge cannot be solved with the .endsWith()


My Working Code:

function confirmEnding(str, target) {
  var targetLength = target.length;
  var anyString = str.substring(str.length - targetLength);
  return anyString == target;
}


Tests in needs to pass:

console.log(confirmEnding("Bastian", "n")); //should return true.
console.log(confirmEnding("Connor", "n")); //should return false.
console.log(confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification")); //should return false.
console.log(confirmEnding("He has to give me a new name", "name")); //should return true.
console.log(confirmEnding("Open sesame", "same")); //should return true.
console.log(confirmEnding("Open sesame", "pen")); //should return false.
console.log(confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain")); //should return false.
You could use substr and pass it a negative number. Doing so is the equivalent of str.substring(str.length - X). That means you just have to pass -target.length.



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

function test(str, target, expected) {
  let testName = `"${str}" ${expected ? 'ends' : 'does not end'} with "${target}"`;
  if (confirmEnding(str, target) === expected) {
    console.log(`PASS: ${testName}`);
  } else {
    console.log(`FAIL: ${testName}`);
  }
}

test("Bastian", "n", true);
test("Connor", "n", false);
test("Walking on water and developing software from a specification are easy if both are frozen", "specification", false);
test("He has to give me a new name", "name", true);
test("Open sesame", "same", true);
test("Open sesame", "pen", false);
test("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain", false);