Hey guys, I’m currently working my way through the algorithm section and its very rewarding coming up with a way to solve any of the problems.
I’ve just solved the ‘Confirm the ending’ algorithm challenge and I used some code that did the job but I have a feeling it was probably not the straightforward way of doing it.
I was wondering which way you solved it and what your code looked like, this is mine:
function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
var arr = str.split(" "); //split the string up into an array of words
var lastWord = arr[arr.length-1];
if (lastWord.substr(-target.length) === target) {
return true;
}
return false;
}
confirmEnding("Bastian", "n");
I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.
Also, here’s my solution:
function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
return target === str.substr(str.length - target.length, str.length);
}
confirmEnding("Bastian", "n");
It’s an old solution (which dates back to the day I started FCC).
I tried this again differently:
function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
return new RegExp(target + '$').test(str);
}
confirmEnding("Bastian", "n");
function confirmEnding (str, target) {
return str.endsWith(target);
}
// but it won't work everywhere :
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith#Browser_compatibility
another way, using slice :
function confirmEnding(str, target) {
return str.slice(-target.length) === target;
}
The first argument, str.length - target.length, marks where the substring in str should start. The second argument, str.length, tells how long the substring should be.
I should have used target.length for the second argument instead, since the substring I needed to get has the same length as target.
This is how I solved this problem. Just giving an alternative.
function confirmEnding(str, target) {
// “Never give up and good luck will find you.”
// – Falcor
return str.substr(target.length * -1, target.length) === target;
}
function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
//First: Target strign length
var targetLength = target.length;
// Second: extract size caracters
var position = str.length - target.length;
var extractStr = str.substring(position);
// Third: Compare target with extract
if (extractStr === target) return true;
return false;
}
confirmEnding("Bastian", "n");