2.9 KiB
2.9 KiB
title
| 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
slicemethod copy the string. - In order to get the last characters in
strequivalent to thetarget's length we use theslicemethod. - The first parameter inside the
slicemethod 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
strand 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
targetand check if they have the same characters.
Relevant Links
Advanced Code Solution:
(using Regular Expression)
function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
let re = new RegExp(target+'$','i');
return re.test(str);
}
console.log(confirmEnding("Bastian", "n"));
Code Explanation:
- We need to make a pattern from the
targetvariable that exists at the end of the stringstr. - Since we will use a variable that will change the pattern each time the function is called, we will use the constructor of the regular expression object
new RegExp(pattern[, flags]), so we start with:new RegExp(target). - Then we have to check at the end of the string, so we concatenate to the
targetvariable the$character to match the end:new RegExp(target+'$'). - We use the flag
ito ignore the case of the pattern and we have our completed RegExp:new RegExp(target+'$','i'), or we can ommit the flag entirely. - Finally, we are using our regular expression with the
testmethod to the given string, to check if the string ends with the pattern and return true or false accordingly.