Skip to main content

字符串与数字处理

千分位格式化

正则(\B 匹配非单词边界,前瞻确保后面是 3 的倍数个数字):

function thousands(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
thousands(1234567); // "1,234,567"

工程中直接用 (1234567).toLocaleString()Intl.NumberFormat,但要会写正则版。带小数时需先按 . 分割整数部分再处理。

大数相加

超过 Number.MAX_SAFE_INTEGER(2^53 - 1)的整数相加会丢精度,需用字符串模拟竖式加法:

function addBigNumber(a, b) {
let i = a.length - 1;
let j = b.length - 1;
let carry = 0;
let res = "";

while (i >= 0 || j >= 0 || carry) {
const x = i >= 0 ? +a[i--] : 0;
const y = j >= 0 ? +b[j--] : 0;
const sum = x + y + carry;
res = (sum % 10) + res;
carry = Math.floor(sum / 10);
}
return res;
}

addBigNumber("9007199254740991", "1234567899999999999"); // 精确结果

现代环境也可用 BigIntBigInt(a) + BigInt(b)

中划线 / 下划线转驼峰

const toCamelCase = (str) =>
str.replace(/[-_](\w)/g, (_, c) => c.toUpperCase());

toCamelCase("background-color"); // "backgroundColor"
toCamelCase("user_name"); // "userName"

驼峰转中划线:

const toKebabCase = (str) =>
str.replace(/([A-Z])/g, "-$1").toLowerCase();

toKebabCase("backgroundColor"); // "background-color"

翻转字符串中的单词

const reverseWords = (s) => s.trim().split(/\s+/).reverse().join(" ");
reverseWords(" the sky is blue "); // "blue is sky the"