Reputation: 439
function confirmEnding(str, target) {
var end = target;
var match = '';
for(var x = 0; x < str.length; x++){
for(var j = 0; j < str[x].length; j++){
if(str[x][j]){
match = str[x][j];
}
}
}
return match.substr(-target.length) === target;
}
confirmEnding("He has to give me a new name", "name");
but I want to know if I can instead loop through the string and then check it using the appropriate indexes.
Can someone understand my approach and let me know how/why it's not doable?
It's currently only checking for the last character, so whole words aren't working. I know the line below will work
return str.substr(-target.length) === target;
will work, but can someone help me with my approach
Edit:
I changed it more slightly, and got closer but still no luck.
function confirmEnding(str, target) {
for(var x = str.length-1; x < str.length; x++){
for(var j = target.length-1; j>=0; j--){
if(str[x] === target[j]){
return true;
} else{
return false;
}
}
}
}
confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification");
That returns true, when it should return false. I see why, but thinking of a resolve.
Upvotes: 0
Views: 74
Reputation: 20744
If using the loop is a strict requirement, then I would do it in a way
function confirmEnding(source, target) {
var lengthT = target.length;
var lengthS = source.length;
for(var x = 0; x < lengthT; x++) {
if(source[lengthS - 1 - x] !== target[lengthT - 1 - x]) {
return false;
}
}
return true;
}
confirmEnding("He has to give me a new name", "name"); // true
But the easier implementation of confirmEnding
method would be just
function confirmEnding(source, target) {
return source.substr(source.length - target.length, target.length) === target;
}
Upvotes: 1