First of all, here is my code snippet:
const Reg = new RegExp("nmElk and the pol (nmélk et les pol)","ig");
console.log(Reg.test("nmElk and the pol (nmélk et les pol)")); //false
The result of the above codes comes out false, but when I separate them like below to test them it comes out true.
const Reg1 = new RegExp("nmElk and the pol","ig");
const Reg2 = new RegExp("(nmélk et les pol)","ig");
console.log(Reg1.test("nmElk and the pol")); //true
console.log(Reg2.test("(nmélk et les pol)")); //true
I have no idea which parts are wrong and confused.
I want to make the regular expression comes out as the true result for the first code.
Anything I should revised or should I use other approaches?
Thanks in advance 🙂
>Solution :
Parentheses have a special meaning in a regular expression. If you want literal parentheses, then you need to escape them with a backslash.
In case you build your regex using the RegExp function and a string literal, then you need to escape that backslash also — with another backslash:
const Reg = new RegExp("nmElk and the pol \\(nmélk et les pol\\)","ig");
console.log(Reg.test ("nmElk and the pol (nmélk et les pol)")); //true
However, since there is nothing dynamic to your regex, it would be more appropriate to use a regex literal:
const Reg = /nmElk and the pol \(nmélk et les pol\)/ig;
console.log(Reg.test ("nmElk and the pol (nmélk et les pol)")); //true