I am trying tor write this function that Check if a string (first argument, str) ends with the given target string (second argument, target). I have used this code but it seems not to work. How can i tweak it?
function confirmEnding(str, target) {
var last = str.substring(-1);
var last2 = target.substring(-1);
if (last == last2) return true;
else if (last !== last2) return false;
}
confirmEnding("Walking on water and developing software from a specification
are easy if both are frozen", "specification") )/*should return "false".
confirmEnding("Bastian", "n") should return true.
confirmEnding("Connor", "n") should return false.
confirmEnding("Walking on water and developing software from a specification
are easy if both are frozen", "specification") should return false.
confirmEnding("He has to give me a new name", "name") should return true.
confirmEnding("Open sesame", "same") should return true.
confirmEnding("Open sesame", "pen") should return false.
confirmEnding("If you want to save our world, you must hurry. We dont know
how much longer we can withstand the nothing", "mountain") should return
false.
Do not use the built-in method .endsWith() to solve the challenge.*/
In order to pass all of the tests with the desired return values, the function should not be comparing the last character of the string, but rather the entire string, target
to the corresponding end substring of str
. You need the length of target
to find the correct starting index for the corresponding substring in str
as follows:
function confirmEnding (str, target) {
return str.substring(str.length - target.length) === target)
}
Your code is comparing the entire strings. See substring()
documentation below. -1
is defaulting to 0
thus returning the substring starting at index 0
and returning the rest of the string (the entire string) since no end index is given. .
"If either argument is less than 0 or is NaN, it is treated as if it were 0."
You can use the length of target
and subtract it from the length of str
to get the correct substring for comparison. This will return all of the characters from this index to the end of the string as in str.length - target.length
though you only really need target.length
to make the comparison using negative indices.
Using substring():
function confirmEnding (str, target) {
var last = str.substring(str.length- target.length);
return last === target;
}
simplified:
function confirmEnding (str, target) {
return str.substring(str.length - target.length) === target)
}
substring() documentation
UPDATE: substr()
is now deprecated, answer updated to use substring()
only.