Differences between new RegExp(pattern) and pattern.test(string) [duplicate]

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.

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.

  • you may find your answer to here stackoverflow.com/questions/10940137/…

    – 

  • That’s right, thank you. Sorry for the duplicate post

    – 

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/')

Leave a Comment