Confirm the Ending help pls

Can we solve Confirm the Ending problem using regular expressions?

Your code so far


function confirmEnding(str, target) {
  // "Never give up and good luck will find you."
  // -- Falcor
 let x=str;
  let m=/target$/;
 console.log(m.test(x));
  
 
}

console.log(confirmEnding("Bastian", "n"));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

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

What you have written basically means that it finds the “target” word at the end of the string. For this you need to use RegExp constructor to make a new regex contains the argument content, otherwise it’s just the string name.

let m= new RegExp(target+"$");

my new code would be
: function confirmEnding(str, target) {
// “Never give up and good luck will find you.”
// – Falcor
let x=str;
let m= new RegExp(target+"$");
console.log(m.test(x));

}
but still could not pass the test

You forgot to return it at the end of the function

return m.test(x);

1 Like

side note, the let x = str; is absolutely unnecessary. str is perfectly serviceable not to mention more descriptive.

the let m = new RegExp(target + "$"); could be useful if you are going to be using it a lot or the regex is hard for a human to figure out, but then you would want a descriptive name like testEnding. In this case, where you are just using it once and it is pretty straight forward, there is no reason not to just do: return RegExp(target + "$").test(str);

As a general rule, you should be able to figure out what a variable is or a function does by reading the name without having to look back at the declaration. Future you will thank you as will others reading your code.

With the exception of a few traditional uses (for example, i and j for loops and inner loops), unless you are game programming (or perhaps embedded code) where every bit counts, you almost never want to use a single letter variable name.

Sure, these are just exercises, but “perfect practice makes perfect.” Habits formed now will carry on to your career later.

@tkhquang :smile:oops forgot that…thnk you…

@ChadKreutzer: FCC is like a goldmine for a novice like me…Would definitely remember your advice while naming variables…Thank you soo much…:grinning:

1 Like