Confirm The Ending w/RegEx

Confirm The Ending w/RegEx
0

#1

Okay, so I do not understand why this code doesn’t work. I’m not looking for a solution to the FCC exercise (I figured out another way), but rather just an explanation of why this doesn’t work because I’m not getting it.

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

confirmEnding("Conner", "r");

This returns false. However, if I replace /target$/ with /r$/ it works even though target is equal to r when it’s passed in as an argument in the function.

Super confused, but thankful for the help.


#2

I’m not an expert on this, but I believe targetReg is setting your RegExp to search for “target” at the end of a string. If you log targetReg to the console, you’ll get /target$/ rather than the target being passed into the function (in this case, “r”). So, you would need to find a way to combine the target with the necessary components of your RegExp (think concatenation using +). You may also find this doc helpful, especially the very beginning that shows using the new RegExp constructor option.

Hope that helps!