I have this regex that checks for a 5 digit number ^\d{5}$
How do I change it so that it returns true also for an empty string?
<script type="text/javascript">
var regex = /^\d{5}$/;
alert(regex.test(12345));
alert(regex.test(''));
</script>
Enclose it in ()
and add a ?
to make the entire pattern optional. Effectively, you are then either matching ^\d{5}$
OR ^$
(an empty string).
var regex = /^(\d{5})?$/;
console.log(regex.test(12345));
console.log(regex.test(''));
// true
// true
// Too long, too short
console.log(regex.test(123456));
console.log(regex.test('1'));
// false
// false
Note that unless you intend to do something with the 5 digits other than prove they are present, you can use a non-capturing group (?: )
to save a tiny bit of resources.
var regex = /^(?:\d{5})?$/;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With