Basic Algorithm Scripting: Confirm the Ending

Hello…

my solution to this…is this okay? it works.

Summary

function confirmEnding(str, target) {
// “Never give up and good luck will find you.”
// – Falcor
var noob = str.length; //get string length
var noob2 = target.length; //get length of target
var result = str.substring(noob-noob2); //here subtract lengths of string and target to extract equivalent end of string
var match = target.substring(); //here outputting target
console.log(match);
console.log(result);
if (match == result){ //matching both sub string outputs
return true;
}
else{
return false;
}

}

confirmEnding(“Bastian”, “n”);

Looks good to me. You could certainly make it shorter in some ways.

For example, this

if (match == result) {
  return true;
} else {
  return false;
}

could just be

return match == result;
1 Like

Hi,

It gets the job done, so congrats! :slight_smile:

The useless line is var match = target.substring(); because substring without any arguments will always return the target string, so that line means var match = target and you already have a variable with that value: target.

This is your code without that line:

function confirmEnding(str, target) {
  var noob = str.length;
  var noob2 = target.length;
  var result = str.substring(noob - noob2);
  if (target == result) {
    return true;
  } else {
    return false;
  }
}

You can improve it the way @michaelfoland just told you:

function confirmEnding(str, target) {
  var noob = str.length;
  var noob2 = target.length;
  var result = str.substring(noob - noob2);
  return target == result;
}

Have you seen regular expressions already? I think this example is a good fit for that:

function confirmEnding(str, target) {
  return new RegExp( target + "\$" ).test( str );
}

Happy coding!

1 Like

Clear “for” loop


let result = "";
  for (let c = 0; c < target.length; c++) {
    result += str[c + (str.length - target.length)];
  }

  return (result === target) ? true : false;