---
description: 🚧 under construction
---

# JS-style numbers

[JS](../../../..) ⟩ [value](../../..) ⟩ [object](../../../obj) ⟩ [regex](..) ⟩ [example]() ⟩ JS-style numbers

{% tabs %}
{% tab title="💈範例" %}
* replit ⟩ [JS-style numbers](https://replit.com/@pegasusroe/regex-JS-style-numbers#index.js)

```javascript
'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 ...
```
{% endtab %}

{% tab title="📗 參考" %}
* [ ] Eloquent JS ⟩ Regular Expressions ⟩ [Numbers again](https://eloquentjavascript.net/09_regexp.html#i_izldJoT3uv)
{% endtab %}

{% tab title="👥 相關" %}
* [use](../use "mention")
{% endtab %}
{% endtabs %}
