freeCodeCamp Challenge Guide: Confirm the Ending

Confirm the Ending


Solutions

Solution 1 (Click to Show/Hide) (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");

Code Explanation

  • First we use the slice method copy the string.
  • In order to get the last characters in str equivalent to the target's length we use the slice 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 return give 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 of target, that way, we shall get the last remaining characters equivalent to the target's length.
  • Finally we compare the return result of slice to target and check if they have the same characters.

Relevant Links

Solution 2 (Click to Show/Hide) (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 target variable that exists at the end of the string str.
  • 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 target variable the $ character to match the end: new RegExp(target+'$').
  • We use the flag i to 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 test method to the given string, to check if the string ends with the pattern and return true or false accordingly.

Relevant Links

Solution 3 (Click to Show/Hide)
function confirmEnding(str, target) {
  return str.slice(-target.length) === target
}

confirmEnding("Bastian", "n");

Code Explanation

  • If a negative number is provided as the first parameter to slice() , the offset is taken backwards from the end of the string.
179 Likes

Great explanation! Thanks for breaking it down into such simple terms.

12 Likes

I used this method to do this exercise, longer but effective.

function confirmEnding(str, target) {
// “Never give up and good luck will find you.”
// – Falcor
var targetLength = target.length;
var sub = str.slice(-targetLength);
if(sub === target){
return true;
}
return false;
}

confirmEnding(“open sesame”, “same”);

27 Likes

I used this

function confirmEnding(str, target) {
  
    if (str.substr(str.length -target.length,str.length) !== target){
      return false;
    } else{
      return true;
    }
  
  return str;
}

confirmEnding("He has to give me a new name", "name");
```
21 Likes

function confirmEnding(str, target) {
// “Never give up and good luck will find you.”
// – Falcor
return (str.lastIndexOf(target) === str.length - target.length) ? true : false;
}

confirmEnding(“Bastian”, “n”);

13 Likes

Here is the way I solved this; this one took some thinking!

function confirmEnding(str, target) {
// “Never give up and good luck will find you.”
// – Falcor
var anyString = str.length;
var x = target.length;
var anyStringLast = str.substring(anyString - x);
return anyStringLast === target;
}

5 Likes

Why so complicated? Any compare operator returns true or false, so we don’t need no additional true-false.
Just:
return str.substring(str.length - target.length) === target;

43 Likes

Here is my solution:

function confirmEnding(str, target) {

return str.substr(str.length - target.length) === target;
}
//test
confirmEnding(“Bastian”, “n”);

11 Likes

I solved my own using this code snippet:

function confirmEnding(str, target) {
for(var i = 0; i < str.length; i++){
if(str.substr(i-str.length) === target){
return true;
}
}
return false;
}
confirmEnding(“Bastian”, “n”);

6 Likes

Hi - don’t think I saw this approach being used yet, also a bit longer - adds an identifier onto the end of the string, and using the target to split the string it tests whether the identifier at the end of the string was successfully split off:

function confirmEnding(str, target) {
// “Never give up and good luck will find you.”
// – Falcor

var str2 = str.concat(“test”);
var split = str2.split(target);

if (split[split.length-1]===“test”) {return true;}
else {return false;}

}

confirmEnding(“Bastian”, “n”);

8 Likes

var v = str.substr(str.length-target.length );
if (target===v){
return true;
}
else {
return false;
}
return str;
}

3 Likes

Now, I always thinking that operator returns true or false. For the challenge, i’ll reduce my code at a “if” with return true or flase. I learn every days. :wink:

3 Likes

I used this approach to solve the problem:

function confirmEnding(str, target) {
var arr = ;
var string = str.split(“”);
for(var i = 1; i <= target.length; i++){
arr.push(string.length - i);
}
arr.sort(function(a, b){return a - b;});
var arr1 = ;
for(var j = 0; j < target.length; j++){
arr1.push(string[arr[j]]);
}
if(arr1.join(“”) === target){
return true;
}
return false;
}

I first converted “str” into an array of letters then i used a for loop to push to the array “arr” letters from the end of the “string” array equal to the length of the “target”, then i sort the array “arr” in an ascending order then i create another array “arr1” and used another for loop to push to the array “arr1” the actual letters that “arr” array refer to it using numbers after that i compared ‘arr1.join(“”)’ string to the “target” string if equal in value and type then return true, if not return false.

3 Likes

Nice, that went really smooth for a change. Almost exactly like the provided solution, just with unnecessary length-checking.

return str.substr((str.length - target.length)) === target;

I took a look at the endsWith() function and it seems to work as follows:

    if (!String.prototype.endsWith) {
      String.prototype.endsWith = function(searchString, position) {
          var subjectString = this.toString();
          if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
            position = subjectString.length;
          }
          position -= searchString.length;
          var lastIndex = subjectString.indexOf(searchString, position);
          return lastIndex !== -1 && lastIndex === position;
      };
    }
4 Likes

function confirmEnding(str, target) {
var tl = target.length;
var sl = str.lenght;

var controle = str.substring(str.length-tl,str.length);
return controle==target;
}

confirmEnding(“Bastian”, “n”);

1 Like

function confirmEnding(str, target) {
var targetLength = target.length,
finalStr = str.substr(-targetLength),
trueOrFalse;

if(finalStr === target){
trueOrFalse = true;
} else {
trueOrFalse = false;
}

return trueOrFalse;
}

confirmEnding(“Bastian”, “n”);

2 Likes

Basic solution
This is done without substr, simple procedural reasoning,
linear type.

function confirmEnding(str, target) {
  for (var i = 0; i < target.length; i++) {
    if (target[target.length - 1 - i] != str[str.length - 1 - i]) {
      return false;
    }
  }
  return true;
}
10 Likes

I must have the most complicated and embarrassing approach of all:

function confirmEnding(str, target) { var array = str.split(" "); if (array.length == 1 && array[0].substring(array[0].length - 1) == target) { return true; } var lastWord = array[array.length - 1]; if (lastWord.substring(lastWord.length - target.length) == target){ return true; } return false; I got arrays on the brain.
4 Likes