JavaScript / ECMAScript

JSON Number (Strict) in JS

Match JSON-spec numbers — disallows leading zeros (no `01`), allows decimals and exponents.

Try it in the JS tester →

Pattern

regexJS
-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][-+]?\d+)?   (flags: g)

JavaScript / ECMAScript code

jsJavaScript
const re = new RegExp("-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][-+]?\\d+)?", "g");
const input = "values: 0, 42, -3.14, 6.022e23";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));

Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).

How the pattern works

-? optional sign. (?:0|[1-9]\d*) the integer part: either a single zero or a non-zero digit followed by any digits (no leading zeros allowed per RFC 8259). (?:\.\d+)? optional decimal part. (?:[eE][-+]?\d+)? optional exponent. Strict per JSON spec — won't match `01` or `1.` (which are valid JS but not JSON).

Examples

Input

values: 0, 42, -3.14, 6.022e23

Matches

  • 0
  • 42
  • -3.14
  • 6.022e23

Input

0.5 vs invalid 01

Matches

  • 0.5
  • 0
  • 1

Input

no numbers

No match

Same pattern, other engines

← Back to JSON Number (Strict) overview (all engines)