Last active
October 4, 2015 01:37
-
-
Save svahora/f7ce9518a05e257a74b7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
commented
Aug 4, 2015
You also can do like bellow example !
function end(str, target) {
return str.substr(str.length- target.length) === target ? true : false;
}
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:
- Set up your function
- Inside of that, type:
return ( /* this is where your evaluation goes */ );
. This will cause the function to returntrue
if your evaluation is true, andfalse
if your evaluation is false. There's no need to type out if, else, true or false. - 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)
- 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