Basic Algorithm Scripting: Confirm the Ending + regex

Basic Algorithm Scripting: Confirm the Ending + regex
0

#1

Hi Campers!

Regarding this task

I wonder is it possible to solve it using RegEx?

First I tried this way:

function confirmEnding(str, target) {
  let regex = new RegExp(target);
  return regex.test(str);
}

And It almost worked … Why almost? Because I forgot about $.
When I changed to :

function confirmEnding(str, target) {
  let regex = new RegExp(target$);
  return regex.test(str);
} 

It crashed… Can anyone tell me, is that possible to solve that task via RegEx?

Thank You!


#2

Why did you put $ on the end of the variable named target?

Yes, it is possible to use a regular expression to solve this challenge. See if you can figure out how.


#3

Thank You! : )
Your hint helped…
Is there more “beautiful” way for that, than mine?

Spoiler
function confirmEnding(str, target) {
  let regexEnd = target + '$';
  let regex = new RegExp(regexEnd);
  return regex.test(str);
}

#4

You could skip the extra variable if you wanted.

let regex = new RegExp(target + '$');

OR

let regex = new RegExp(`${target}$`); // uses a String Literal

#5

Perfect!
Thanks a lot!