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

Differences between new RegExp(pattern) and pattern.test(string)

I try to create a strong password rule for JavaScript with regex. However, i find a strange result using different approach.

First approach (worked):

const value = 'TTest90()';
const firstApproach = /^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2,})(?=(.*[!@#$%^&*()\-_+?.]){2,}).{8,}$/.test(value);

The variable firstApproach is true witch is intended result.

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

The next approach is using the new RegExp like:

const pattern = '/^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2,})(?=(.*[!@#$%^&*()\-_+?.]){2,}).{8,}$/';
const regex = new RegExp(pattern);
const secondApproach = regex.test(value);

But, secondApprocach now is false with the same regex.

I can’t find why secondApproach variable isn’t true because is the same regex.

I am asking this question because I want to understand where I am going wrong. Thank you.

>Solution :

You should not put the "/" inside the string in your pattern.

More specifically, the /..../ is a specific javascript syntax to create a RegExp.

So /something/ is like writing new RegExp('something'). You are instead writing new RegExp('/something/')

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