I have the following Regular Expression, how can I modify it to also allow null?
null|^$|^([A-Za-z]{2}\d{8}[A-Za-z]{2})$
I would like it to allow a 2 alphabet 8 digit number 2 alphabet, or empty, or null
CodePudding user response:
You're trying to match the string literal 'null' to a primitive value.
Regex will only work with string literals. you can use the regex ^([A-Za-z]{2}\d{8}[A-Za-z]{2})$
to match 2 alphabets followed by 8 digits and 2 alphabets.
Then you can explicitly compare a variable to null, use a simple regex to remove all whitespace and compare it to an empty string to check if it is empty or not
const regex = /^([A-Za-z]{2}\d{8}[A-Za-z]{2})$/g;
const string = ' ';
// const string = null; // will pass the test
// const string = 'ab12345678cd'; // will also pass the test
const passRegex = regex.test(string);
if (passRegex || string == null || string.replace(/\s/g, '') == '') console.log('string passes the test');
else console.log('string does not pass the test :(');
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>