Using template literal inside of a regex

Tell us what’s happening:
May be I am going about this the wrong way, I am trying to use a regex to search for the target string at the end of the string. I attempted to use the target as a changeable variable. Only it is not working as intended.
Your code so far

function confirmEnding(str, target) {

let myRegex = /`${target}`$/
let result = myRegex.test(str)

return result;

confirmEnding("Bastian", "n");

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36.

Challenge: Confirm the Ending

Link to the challenge:

Remember that regex is not a string. You can convert a string to regex, as explained here.

Here is a discussion on stackoverflow about this issue How do you use a variable in a regular expression?

But by far the easiest way to solve this is by using something like String.prototype.lastIndexOf();

a user can use a Template literal inside of a regular expression.

Yes, you can. A template literal resolves to a string. You can convert strings to regex. You build your string (with a template literal if you want) and then convert it to regex with the method shown in the links above.

Thanks for your help. Wanted to share my script for future refrence.
Spoiler Below

  const a = target
  const regex2 = new RegExp(`${a}$`,)
  let result = regex2.test(str)

  return result;

confirmEnding("Bastian", "n");

Cool. Yeah, that’s what I was thinking. I’d only add that the comma probably isn’t needed there:

1 Like

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