Confirm the Ending using Regular Expression

Tell us what’s happening:

How come this regular expression doesn’t work to test if the ending of the string is the target string?

Your code so far


function confirmEnding(str, target) {
  // "Never give up and good luck will find you."
  // -- Falcor
  let isThisTheEnd = /target$/;
  if (isThisTheEnd.test(str) === true) {
    return true;
  }
  else {
    return false
  }
}
console.log(confirmEnding('Bastian','n'));
confirmEnding("Bastian", "n");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

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

The regular expression here matches exactly the word “target” instead of matching whatever is stored in a variable.

Thanks! I thought that might be the case. Do you know if there is a way to use the $ regular expression to solve this problem?

If you want to use variables in a Regular Expression, you will need to create one using the RegExp constructor. You can read a bit about that on MDN.

In the following example, if I wanted to pass a pattern to my function and turn it into a Regular Expression, I would do:

function someFunc(str, pattern) {
  var myRegEx = new RegExp(pattern, 'i');
  
  if (myRegEx.test(str)) {
    console.log('Wheeee. It matches!');
  }
}

someFunc('I love cats', '^I love');