function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
let re = new RegExp(target + "$", "i");
return re.test(str);
}
console.log(confirmEnding("Bastian", "n"));
Do we need the “new”. In the explanation it says because we will use a variable that will change the pattern each time the function is called.
But wont the “target” in the Regex change by itself without the use of “new”?
Also why does the code do (target + $)? Isnt the syntax like this (target$)
This is so you don’t modify the original prewritten code, because the “new” literally means create a new variable that uses that function.
See, target"$" is different that target$. target$ can be a variable, but target"$" means the variable/parameter target with the syntax “$”. So it’s not the same.
function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
let re = new RegExp(target + "$", "i");
return re.test(str);
}
console.log(confirmEnding("Bastian", "n"));
in Regex, the syntax “$” means beginning of a string or end of a string depending where you put it. So “n$” means end with “n”. So if its “$n”, it means start with “n”.
As @ILM said, That would be a syntax error. You cannot put in spaces in variables or parameter unless it is inside a string. So as @ILM already said again, target $ will spit out Syntax Error.
in that case you would write a regular expression literal, which you can totally do if you don’t need to change anything, like re = /n$/i;
but in the code you posted you are creating a regular expression from a variable, and in that case you need to use string methods and operators
The syntax \ means escaping, that means the code will see it as it’s own thing. for example “$” in regex means end of string, but if you do \$, it will be escaped into a simple “$” string.
if you use new RegExp it will be that that will put the / in the regular expression
if you do let re = new RegExp(<a>, <b>);
it creates a regular expression like /<a>/<b>
Please note that you still need to consider the general escaping rules for strings, for example if you want a backslash in the string you need to escape it and so write \\