TASK: Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
MY SOLUTION:
function solution(str, ending) {
if (str.slice(-1) === ending.slice(-1)) {
return true;
}
return false;
}
console.log(
solution('sumo', 'omo') // returned false!!!
)
You can use String.prototype.endsWith.
function solution(str1, str2) {
return str1.endsWith(str2);
}
console.log(solution("football", "ball")); // true
console.log(solution("football", "foot")); // false
console.log(solution("football", "oot")); // false
If you want the comparison to be case insensitive, then you can compare the lowercase version of both the strings.
function solution(str1, str2) {
return str1.toLowerCase().endsWith(str2.toLowerCase());
}
console.log(solution("FOOTBALL", "ball")); // true
console.log(solution("footBall", "BALL")); // true
You can do something like this
function solution(str, ending) {
if (str.includes(ending)) {
return true;
}
return false;
}
console.log(solution("football", "ball")); // true
console.log(solution("football", "foot")); // true
console.log(solution("sumo", "um")); // true
A more modern version (ES6+) of the function declaration would be this oneliner
const solution = (str1, str2) => str1.endsWith(str2);
If you need case insensitive testing. you can also construct a regular expression so you do not need to lowerCase.
Remove the "i" to leave it case sensitive
const solution = (str1, str2) => new RegExp(str2+"$","i").test(str1);
console.log(solution("football", "ball")); // true
console.log(solution("football", "Ball")); // true
console.log(solution("football", "foot")); // false
console.log(solution("sumo", "um")); // false