Confirm the Ending - JavaScript Solution & Walkthrough
(06/16) Learn how to solve coding challenges using FreeCodeCamp's curriculum.
06/16 Confirm the Ending
Check if a string (first argument,
str
) ends with the given target string (second argument,target
).This challenge can be solved with the
.endsWith()
method, which was introduced in ES2015. But for the purpose of this challenge, we would like you to use one of the JavaScript substring methods instead.
function confirmEnding(str, target) {
return str;
}
confirmEnding("Bastian", "n");
Credit: FreeCodeCamp.org
Understanding the Challenge
Here in this challenge, you'll be given two arguments. Both will be strings. The first string str
and the second string target
. Your task is to create a function that verifies whether the first string str
ends with the same letters as the second string target
.
For example if str
is given as "hello" and target
is "lo", your function should return true. However, if str
is given as "coding" and target
is "gin", your function should return false.
Your function is thus expected to return a true or false based on whether the ending of str
is the same as given target
.
Pseudocode
Given str and target
Find length of str
Extract the last x characters of str
(x should be equal to length of target)
Compare last x characters of str to target
Return true if they are equal and false if they are not
Solving the Challenge
First let's declare a variable strLength
. We will assign to this variable the length of str
.
const strLength = str.length;
Next, we need to find the last x
characters of str
. And keep in mind that x
should be equal to the length of target
.
To get that we need to first subtract the length of that target
from the length of str
. Let's assign that to a variable called subLength
const subLength = str.length - target.length;
Now, we can use .substring()
to get the last x
letters of the given string. Let's assign the result to a variable called lastLetters
const lastLetters = str.substring(subLength, strLength);
The .substring()
helps us to extract part of a string. The first argument, which in this case is subLength
helps us to get the starting point of the extraction. And the second argument helps us to get the end point of the extraction. In this case, because we are using strLength
, the end point of the extraction will always be the end of the given string.
Now, all that is left to do is to compare the variable lastLetters
with the given target
.
return (lastLetters === target);
If they're equal, our function should return true
. Otherwise, our function should return false
Final Solution
function confirmEnding(str, target) {
const strLength = str.length;
const subLength = str.length - target.length;
const lastLetters = str.substring(subLength, strLength);
return (lastLetters === target);
}
confirmEnding("Bastian", "n"); // true
Congratulations!
You just cracked the sixth challenge in this series.
Cheers and happy coding!