Basic Algorithm Scripting: Confirm the Ending + regex

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!

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.

1 Like

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

Perfect!
Thanks a lot!

Hi

please could you explain a little about this RegExp solution. The RegExp constructor function was not covered in the Regex lessons and I am a bit confused. Why is it written here as

RegExp(target + '$')

?

Hi Bro!!
I am new here !

I am just confused of what I should learn
Java or Kotlin
??
:sweat_smile::sweat_smile::sweat_smile::sweat_smile:

Hi

thank you for your reply Randell. I looked at both the MDN guide and the reference, but could not find any information on the particular syntax you used. From the MDN reference I found:

"There are 2 ways to create a RegExp object: a literal notation and a constructor. To indicate strings, the parameters to the literal notation do not use quotation marks while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:

/ab+c/i;
new RegExp('ab+c', 'i');
new RegExp(/ab+c/, 'i');

I am confused about why you have used a + sign, and why is the ‘$’ in quotes.

Thank you so much Randell - this explains it perfectly for me. This syntax with the + sign is concatenating to achieve the desired regex query, which seems blindingly obvious to me now! I can see how powerful this technique is.

I am much happier now that I understand the purpose and meaning of the ‘new Regexp constructor method’.

Thank you for your patience :slight_smile:

1 Like

Hey Randall,
Read through some of the documentation, but I’m still not clear on the difference between these two and was hoping you could help explain it in laymen’s terms?

//where target is an argument passed into the function.
let targetReg = new RegExp (target + '$');  //works
let targetReg = /target$/;         //Doesn't work

When I switch these out, one works and one doesn’t and I simply don’t know why. Thanks!