因为Firefox中无效的regexp组而重写Regex

问题描述 投票:0回答:1

我只在Firefox浏览器中开始收到这个错误。我猜测是这个函数中不支持的lookbehind导致了这个问题。

火狐浏览器中无效的regexp组

我有什么其他方法可以实现这个regex的功能(千位数分隔符)?

function thousand_separator(x) {

    return x.toString().replace(/\B(?<!\,\d*)(?=(\d{3})+(?!\d))/g, ".");
}

enter image description here

javascript regex firefox syntax-error
1个回答
1
投票

看起来这个regex可能是改编自 https:/stackoverflow.coma29012981058183。.

倒过来看这个答案,试试这个。

function thousand_separator(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    return parts.join(".");
}

function thousand_separator(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    return parts.join(".");
}

function test(x, expect) {
    const result = thousand_separator(x);
    const pass = result === expect;
    console.log(`${pass ? "✓" : "ERROR ====>"} ${x} => ${result}`);
    return pass;
}

let failures = 0;
failures += !test(0              , "0");
failures += !test(0.123456       , "0.123456");
failures += !test(100            , "100");
failures += !test(100.123456     , "100.123456");
failures += !test(1000           , "1.000");
failures += !test(1000.123456    , "1.000.123456");
failures += !test(10000          , "10.000");
failures += !test(10000.123456   , "10.000.123456");
failures += !test(100000         , "100.000");
failures += !test(100000.123456  , "100.000.123456");
failures += !test(1000000        , "1.000.000");
failures += !test(1000000.123456 , "1.000.000.123456");
failures += !test(10000000       , "10.000.000");
failures += !test(10000000.123456, "10.000.000.123456");
if (failures) {
    console.log(`${failures} test(s) failed`);
} else {
    console.log("All tests passed");
}
.as-console-wrapper {
    max-height: 100% !important;
}
© www.soinside.com 2019 - 2024. All rights reserved.