字符串与数字
约 393 字大约 1 分钟
布欧-Lewyon
2026-05-16
首页 › JavaScript › JS 基础 › 字符串与数字
字符串方法
let str = ' Hello, JavaScript! ';
// 常用方法
str.length; // 21
str.toUpperCase(); // " HELLO, JAVASCRIPT! "
str.toLowerCase(); // " hello, javascript! "
str.trim(); // "Hello, JavaScript!"
str.includes('Java'); // true
str.startsWith('Hell'); // true
str.endsWith('!'); // true
// 提取
str.slice(0, 5); // " Hel"(从索引 0 到 5)
str.slice(-5); // "ipt! "(倒数 5 个)
str.substring(0, 5); // 同 slice,但不支持负数
str.substr(0, 5); // ⚠️ 已弃用
// 分割与合并
'apple,banana,orange'.split(','); // ["apple","banana","orange"]
['a', 'b'].join('-'); // "a-b"
// 查找
str.indexOf('Java'); // 8
str.lastIndexOf('a'); // 12
str.search(/Java/); // 8
// 替换
str.replace('JavaScript', 'JS'); // 替换第一个
str.replaceAll('a', 'x'); // 替换全部(ES2021)
// 重复与填充
'x'.repeat(3); // "xxx"
'5'.padStart(3, '0'); // "005"
'5'.padEnd(3, '0'); // "500"数字与 Math
// 浮点数精度问题
0.1 + 0.2; // 0.30000000000000004 ❌
// 解决方法
+(0.1 + 0.2).toFixed(1); // 0.3
Math.round((0.1 + 0.2) * 10) / 10; // 0.3
// Number 方法
Number.isNaN(NaN); // true
Number.isFinite(Infinity); // false
Number.isInteger(42); // true
Number.parseInt('123px'); // 123
Number.parseFloat('3.14'); // 3.14
// Math 对象
Math.max(1, 3, 2); // 3
Math.min(1, 3, 2); // 1
Math.floor(3.9); // 3
Math.ceil(3.1); // 4
Math.round(3.5); // 4
Math.random(); // 0~1 随机数
Math.abs(-5); // 5
Math.pow(2, 3); // 8
Math.sqrt(9); // 3BigInt
// 大整数运算
const max = 9007199254740991n;
const big = 123456789012345678901234567890n;
console.log(max + 1n); // 9007199254740992n
console.log(typeof big); // "bigint"小结
| 类别 | 常用方法 |
|---|---|
| 字符串 | includes() startsWith() trim() split() replaceAll() padStart() |
| 数字 | parseInt() toFixed() isNaN() |
| Math | floor() ceil() round() random() max() min() |
| 精度 | 整数运算安全,浮点运算用 toFixed() |
