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>
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>
Share
Improve this question
edited Jun 20, 2012 at 20:33
JimmyPena
8,7646 gold badges45 silver badges65 bronze badges
asked Jun 20, 2012 at 20:18
Registered UserRegistered User
3,69911 gold badges42 silver badges65 bronze badges
1 Answer
Reset to default 12Enclose 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})?$/;