I am trying to work out how to use the $
at the end of a regex that is passed to the new RegExp()
method from a function argument. My code:
function confirmEnding(str, target) {
let r = new RegExp(target, 'i'); // need to make regex only identify pattern at the end
if (r.test(str) == true) {
return true;
} else {
return false;
}
}
Any help would be appreciated.
Thanks
You could concatenate it to the end of target before passing target as an argument to RegExp
.
1 Like
Also, there is no need for an if/else statement here. Since test
returns true
or false
, you can simply return r.test(str)
1 Like
Thanks for your help. I tried this in both node js
and vanilla js
and without the else
statement I get undefined
.
Apologies, I just realised what you meant. This works. My refactored code:
function confirmEnding(str, target) {
var funcTarget = target + '$';
let r = new RegExp(funcTarget, 'i');
return r.test(str);
}