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.
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.
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));
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.