Confirm the Ending Solution 2 has a caveat

Continuing the discussion from freeCodeCamp Challenge Guide: Confirm the Ending:

My first instinct was to reach for a regular expression, and that’s what the author of Solution 2 also did. However, I tested it and realized that it may not work as intended if target contains a punctuation mark. For example:

function confirmEnding(str, target) {
  let myRegEx = new RegExp(target + "$", "i");  // equals to /name?$/i
  return myRegEx.test(str);
}

console.log(confirmEnding("What's your name?", "name?"));

This returns false, because instead of the literal question mark in target the regex engine interprets it as a quantifier for the letter e.

Is there a better way to use a regex in this challenge?

2 Likes

You could parse the string to escape special characters in target first.

2 Likes

Thanks! That helped.

Here is the updated solution, in case anyone needs it:

function confirmEnding(str, target) {
  let parsedTarget = target.split('');

  for (var i in parsedTarget) {
    if ((/[\?\.]+/).test(parsedTarget[i])) {
      parsedTarget[i] = "\\" + parsedTarget[i];
    }
  }

  let myRegEx = new RegExp(parsedTarget.join('') + "$", "i");  // equals to /name\?$/i
  return myRegEx.test(str);
}

console.log(confirmEnding("What's your name?", "name?"));  // returns true
1 Like

Instead of splitting and joining, you could also use a String.replace(), but I’m not sure if you’ve done the more advanced regex stuff yet that would make this work nicely.

I have not, but I will look into it!