DEV Community

Randy Rivera
Randy Rivera

Posted on • Edited on

Checking If A String Ends With The Given Target String

  • Check if a string (first argument, str) ends with the given target string (second argument, target).

  • This challenge can also be solved with the .endsWith() method, which was introduced in ES2015.

function confirmEnding(str, target) {
  return str;
}

confirmEnding("Bastian", "n");
Enter fullscreen mode Exit fullscreen mode

*First let's learn substr:

let sentence = "I'm running in 5 minutes.";
console.log(sentence.substr(2)); // would return "m running in 5 minutes". If (0,5) it would give me the letters that start at 0 and end at 5 not including 5.
// If we're trying to find the end parts of the sentence simply.
console.log(sentence.substr(-2); // would display "s."
// also could be done with endsWith()
if (str.endsWith(target)) {
  return true;
}
 return false;
};
Enter fullscreen mode Exit fullscreen mode

Answer:

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

console.log(confirmEnding("Bastian", "n")); // will display true
Enter fullscreen mode Exit fullscreen mode

Top comments (0)