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>
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Enclose it in
()and add a?to make the entire pattern optional. Effectively, you are then either matching^\d{5}$OR^$(an empty string).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.