6

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>
JimmyPena
  • 8,694
  • 6
  • 43
  • 64
Registered User
  • 3,669
  • 11
  • 41
  • 65

1 Answers1

12

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})?$/;
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390