Confirm the Ending challenge

Hello everyone, can someone tell me if it is possible to use Regular Expressions to complete this challenge.

function confirmEnding(str, target) {
  let lastRegex = /target$/;
  return lastRegex.test(str);
}

confirmEnding("Bastian", "n");

The above code works correctly to return false when target is not at the end of the string for instance in

confirmEnding("Connor", "n") should return false.

But it does not return true for

confirmEnding("Bastian", "n") should return true.

Why is that? I cant figure it out because if I try to do

function confirmEnding(str, target) {
  let lastRegex = /n$/;
  return lastRegex.test(str);
}

confirmEnding("Bastian", "n");

It returns true. Any help will be appreciated, thanks

For future reference, always include a link to the challenge.

Yes, you can definitely use a regular expression to solve this challenge. The issue with your code is that you can’t include a variable like that to create an expression.

let lastRegex = /target$/;

This is literally looking for the string “target” at the end of the string. You’ll want to use a RegExp object instead.

2 Likes

Thanks @bbsmooth I dont know how I missed that.

Next time I will include the link. Thanks alot.

1 Like

Anyone interested in the solution to my question the correct code is

function confirmEnding(str, target) {
  return new RegExp(target + '$').test(str);
}

Which basically confirms whether target is at the end and nothing comes after at. I have understood it as "check whether after target there is nothing "

I added spoiler tags to your solution.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.