gpt4 book ai didi

javascript - 由于Firefox中的正则表达式组无效,导致正则表达式重写

转载 作者:行者123 更新时间:2023-12-03 08:25:14 25 4
gpt4 key购买 nike

我开始仅在Firefox浏览器中收到此错误。我认为导致此问题的原因是此函数内部背后不支持的外观。

Invalid regexp group in Firefox



我可以通过什么其他方式来实现此正则表达式的功能(千位分隔符)?
function thousand_separator(x) {

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

enter image description here

最佳答案

看起来此正则表达式可以从https://stackoverflow.com/a/2901298/1058183改编而来。

向后处理该答案,请尝试以下操作:

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;
}

关于javascript - 由于Firefox中的正则表达式组无效,导致正则表达式重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61883717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com