0

I started receiving this error in Firefox browser only. I assume that unsupported lookbehind inside this function is what causes the problem.

Invalid regexp group in Firefox

What is the other way i could achieve this regex's functionality (number thousand separator)?

function thousand_separator(x) {

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

enter image description here

mr.work
  • 173
  • 10
  • Can you please provide the pass and fail cases for what you want to achieve? –  May 19 '20 at 11:04

1 Answers1

1

It looks like this regex may be adapted from https://stackoverflow.com/a/2901298/1058183.

Working backwards on that answer, try this:

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;
}
Phil Young
  • 1,334
  • 3
  • 21
  • 43