1.4 KiB
1.4 KiB
title |
---|
Confirm the Ending |
Confirm the Ending
🌻 Intermediate Code Solution:
(Declarative approach)
function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
return str.slice(str.length - target.length) === target;
}
confirmEnding("He has to give me a new name", "name");
🚀 Run Code
Code Explanation:
- First we use the
slice
method copy the string. - In order to get the last characters in
str
equivalent to thetarget
's length we use theslice
method. - The first parameter inside the
slice
method is the starting index and the second parameter would be the ending index. - For example
str.slice(10, 17)
would returngive me
. - In this case we only include one parameter which it will copy everything from the starting index.
- We substract the length of
str
and the length oftarget
, that way, we shall get the last remaining characters equivalent to thetarget
's length. - Finally we compare the return result of slice to
target
and check if they have the same characters.