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,630
  • 6
  • 42
  • 64
Registered User
  • 3,601
  • 10
  • 40
  • 63

1 Answers1

11

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
  • 260,803
  • 45
  • 432
  • 377