Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx for 5 digit zip or empty

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>
like image 435
Registered User Avatar asked Jun 20 '12 20:06

Registered User


1 Answers

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})?$/;
like image 145
Michael Berkowski Avatar answered Oct 12 '22 15:10

Michael Berkowski