SoluableNonagon
SoluableNonagon

Reputation: 11752

JS - Regex for number without leading zero, or just zero

I am trying to write a regular expression for currency (no commas or $ signs or periods; just integers), but I am hitting a wall.

I need a the number (as a string) to match a pattern to validate.

The following are what I need:
1. the number can be a single zero
2. the number cannot have leading zeroes

Valid Input: 0 12345 1230

Invalid: 00 012345

What I have so far:

var regex = '^(?!00)([1-9][0-9]*)$';

var testCases = ['0', '12345', '0123', '456', '12340', '00123'];

for (var i in testCases) {
  var result = (testCases[i]).match(new RegExp(regex));
  
  var div = document.createElement('div');
  var textNode = document.createTextNode(testCases[i] + ': ' + !!result);
  div.append(textNode);
  document.querySelector('#results').appendChild(div);
}
<div id='results'></div>

The only thing missing (I feel) is passing for the only 0 case

Upvotes: 2

Views: 5091

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627537

Use the following regex:

/^(?:[1-9][0-9]*|0)$/

Details

  • ^ - start of string
  • (?: - start of an alternation group:
    • [1-9][0-9]* - a digit from 1 to 9 and then any 0+ digits
    • | - or
    • 0 - a 0
  • ) - end of the group
  • $ - end of the string.

See the regex demo.

JS demo:

var regex = /^(?:[1-9][0-9]*|0)$/;
var testCases = ['0', '12345', '0123', '456'];
for (var i in testCases) {
  var result = regex.test(testCases[i]); 
  console.log(testCases[i] + ': ' + result);      
}

Upvotes: 7

Related Questions