โœจJS-style numbers

๐Ÿšง under construction

JS โŸฉ value โŸฉ object โŸฉ regex โŸฉ example โŸฉ JS-style numbers

'use strict';                // toggle sloppy/strict mode
const { log } = console;

// โญ pattern for JS-style numbers
const numberPattern = /^[+\-]?(\d+(\.\d*)?|\.\d+)([eE][+\-]?\d+)?$/;
//                      โ•ฐโ”€1โ”€โ”€โ•ฏ โ•ฐโ”€โ”€โ”€โ”€2โ”€โ”€โ”€โ”€โ•ฏ โ•ฐโ”€3โ”€โ•ฏ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€4โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ
// 1. optional + / -
// 2. digits with optional decimal part
// 3. decimal point (.) with mandantory decimal part
// 4. optional exponent part

const examples = [
    "1", "-1", "+15", "1.55", ".5", "5.",
    "1.3e2", "1E-4", "1e+12",
];

const counterExamples = [
    "1a", "+-1", "1.2.3", "1+1", "1e4.5",
    ".5.", "1f5", ".",
];

let allTestsPassed = true;

// Tests:

for (let str of examples) {
    if (!numberPattern.test(str)) {
        log(`Failed to match '${str}'`);
        allTestsPassed = false;
    }
}

for (let str of counterExamples) {
    if (numberPattern.test(str)) {
        log(`Incorrectly accepted '${str}'`);
        allTestsPassed = false;
    }
}

if (allTestsPassed) log(`โœ… all tests passed ...`);
// โœ… all tests passed ...

Last updated