Skip to content

Instantly share code, notes, and snippets.

@svahora
Last active October 4, 2015 01:37
Show Gist options
  • Save svahora/f7ce9518a05e257a74b7 to your computer and use it in GitHub Desktop.
Save svahora/f7ce9518a05e257a74b7 to your computer and use it in GitHub Desktop.
function end(str, target) {
str = str.split(" ");
if(str.length > 1) {
var length = str.length - 1;
var last = str[length];
if(last === target) {
return true;
} else {
return false;
}
} else {
str = str.join("");
var length = str.length - 1;
var last = str[length];
if(last === target) {
return true;
} else {
return false;
}
}
}
end('Bastian', 'n');
@vancovver
Copy link

screen shot 2015-08-04 at 9 46 51 am

@pehprado
Copy link

You also can do like bellow example !

function end(str, target) {
  return str.substr(str.length- target.length) === target ? true : false;
}

@kaela
Copy link

kaela commented Oct 4, 2015

Since you're simply checking whether something is true or false, you can return what you are evaluating, rather than creating a conditional statement at all.

function end(str, target) {
  return ( target === str.substr(str.length - target.length)  );
}

end("Bastian", "an", "");

Explanation:

  1. Set up your function
  2. Inside of that, type: return ( /* this is where your evaluation goes */ );. This will cause the function to return true if your evaluation is true, and false if your evaluation is false. There's no need to type out if, else, true or false.
  3. For your evaluation, check out the method called substr()
    • substr() typically takes two parameters, but you can enter just one. That one parameter will remove x amount of characters from the beginning of your string, leaving you whatever is left.
    • We can get the number we need by calculating it like so:
      str.length - target.length.
    • Putting the method together, we have str.substr(str.length - target.length)
  4. Now, compare that substring to target so you get a boolean value:
    • target === str.substr(str.length - target.length)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment