Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check Accents and Normal Text with Regular Expression in Javascript

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 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading