-3

If I use this....

var str = 'Testing123@@';

if (str.match(/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!,%,&,@,#,$,^,*,?,_,~,+,\-,",',.,:,=,{,},\[,\],(,)]).{8,}/)) {
  args.IsValid = true;
}

This works fine.

But I updated to try and use a StringLiteral for the '8' so in theory it could be dynamic.

var passwordMinLength = 8;


const regex = new RegExp(`^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!,%,&,@,#,$,^,*,?,_,~,+,\-,",',.,:,=,{,},\[,\],(,)]).{${passwordMinLength},}`);

if (str.match(regex)) {
  args.IsValid = true;
}

Though, this returns false even though in the JS debugger the string output looks the same as the previous implementation. The 8 is showing up as expected.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
JohnPete22
  • 523
  • 3
  • 15

1 Answers1

1

The two regexes are different due to string interpolation. See this comparison from my Notepad++:

enter image description here

You need:

const regex = new RegExp(`^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!,%,&,@,#,$,^,*,?,_,~,+,\\-,",',.,:,=,{,},\\[,\\],(,)]).{${passwordMinLength},}`);
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
  • Yes, based on the referenced article I came to that conclusion as well. But thank you for the text output, I had assumed they looked the same but I was mistaken. – JohnPete22 Feb 18 '21 at 18:33
  • @JohnPete22 A monospaced text editor only misleads under 2 conditions: incorrect output pasting and hidden chars like zero-width space chars and control characters. – MonkeyZeus Feb 18 '21 at 18:35