2

I have some regex that tests against if the string has at least 6 characters. Though I also want it to be true if there is just an empty string also.

Regex:

let regexToTestName = /^[a-zA-Z0-9.!@#$%^&*()_-]{6,}$/g;
let usedName = ''; //or let usedName = 'atLeast6Char';
let isNameMatch = regexToTestName.test(usedName);

As you can see it will work for characters specified of at least 6 in length. But how do I also get a true value if it is an empty string?

0

3 Answers 3

3

Just make your string optional with ?:

/^(\S{6,})?$/

var re = /^(\S{6,})?$/

console.log('', re.test(''));
console.log('a', re.test('a'));
console.log('abcde', re.test('abcde'));
console.log('abcdefg', re.test('abcdefg'));

Sign up to request clarification or add additional context in comments.

Comments

1

The following expression will match the whole string ^ $ for any character . if there's {0} of them (an empty string) or | it will match 6 or more {6,} by specifying a range with only the "from" index, a comma, and no "to" index. The "or" expression must be wrapped in a group ( ).

var re = /^(.{0}|.{6,})$/;

console.log('', re.test(''));
console.log('1', re.test('1'));
console.log('12', re.test('12'));
console.log('123', re.test('123'));
console.log('1234', re.test('1234'));
console.log('12345', re.test('12345'));
console.log('123456', re.test('123456'));
console.log('1234567', re.test('1234567'));
console.log('12345678', re.test('12345678'));

1 Comment

In the process of updating.
0

Use pipe | and grouping to do both.

^([/w]{6,0})|([\w]{0,0})$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.