hamza9
1
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:
Marmiz
2
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
hamza9
3
What’s the role of ‘gmi’ ?
How can i apply this formula in my code ?
Marmiz
4
They were just regular regex flags
(flags doc).
They were there as an example, use the one that suits your needs the best
ILM
5
but the final result is I am a awesome
, isn’t it?
Marmiz
6
It should… let me check it in a REPL…
Yeah, it’s I am awesome
(probably not the best, but I was lacking ideas )
Doesn’t work for you?
ILM
7
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?
Marmiz
8
because it doesn’t… an apparently not only I am bad at copy/pasting but also at reading
Yeah final output: I am a awesome
.
My regex sucks, but should serve to illustrate the point, i hope
ILM
9
make s = "a test"
and you are fine!