Confirm the ending using regex and string methods

Tell us what’s happening:
Sorry if my code is unorthodox but I wanted to understand why my code does not past all the tests. I have made statements that will handle confirming the ending for a statement that has more than one word as well as one that has only one word. I would like to know what I am doing wrong here and how I can make my program look much nicer.

I’m not necessarily looking for an answer, just a little guidance.

Thank you in advance.

Your code so far


function confirmEnding(string,substring){
if (string.search(substring)!==-1){
  let arr = string.split(" ");//I will split sentences into an array that I can use to easily check the last word
  if (arr.length>1 && arr[arr.length-1]==substring){
    return true; //checks for sententences
  } 
  if (arr.length==1){
    let regularExp = new RegExp(substring+"$");
    if (string.search(regularExp!==1)){
      return true;//uses a regualr expression to solve the issue involving main strings with only one word
    }
  }
  else{
    return false; // will return false if substring is in main string but is not at the ending
  }
}
else{
  return false;
}
}
console.log(confirmEnding("He has to give me a new name", "name"));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36.

Challenge: Confirm the Ending

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/confirm-the-ending

The two tests your code currently fails are:

confirmEnding(“Connor”, “n”) should return false.
confirmEnding(“Open sesame”, “same”) should return true.

I suggest modifying your final console.log message to log the output of the failed tests so you can see what is being returned.

In the case of confirmEnding("Connor", "n") why is it returning undefined? Think about your test cases and walk through your logic for that case and see if you can see why that is happening.

In the case of confirmEnding("Open sesame", "same") does anything change if you log the output of confirmEnding("sesame", "same")? What is different from confirmEnding("Open sesame", "same") in terms of what path through the code is taken in each test?

Just a couple of things to ponder.

After you figure out the issues with your current code, I would suggest exploring the substring method and getting the hang of that. You’ll probably find that you can simplify your existing logic if you take time to practice and understand it.

2 Likes