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");
*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;
};
Answer:
function confirmEnding(str, target) {
if (str.substr(-target.length) === target) {
return true;
} else {
return false;
}
}
console.log(confirmEnding("Bastian", "n")); // will display true
Top comments (0)