Regular expression 2

How to use variables in regular expression ?
Thanks for any help !

This isn’t work.

function confirmEnding(str, target) {
const REGEX = /target$/;
return REGEX.test(str);

console.log(confirmEnding("Bastian", "n"));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36.

Challenge: Confirm the Ending

Link to the challenge:

You can create new RegExp object composed by variables:

const s = 'test';
const re = new RegExp(s, 'gmi');
"I am a test".replace(re, 'awesome'); // "I am awesome"

Hope this helps :sparkles:

What’s the role of ‘gmi’ ?
How can i apply this formula in my code ?

They were just regular regex flags (flags doc).

They were there as an example, use the one that suits your needs the best :slight_smile:

but the final result is I am a awesome, isn’t it?

It should… let me check it in a REPL…

Yeah, it’s I am awesome (probably not the best, but I was lacking ideas :slight_smile: )
Doesn’t work for you?

you are replacing “test” with “awesome”
so from “I am a test” you get “I am a awesome”
how are you able to remove the article?

because it doesn’t… an apparently not only I am bad at copy/pasting but also at reading :upside_down_face:

Yeah final output: I am a awesome.

My regex sucks, but should serve to illustrate the point, i hope

make s = "a test" and you are fine!