字串:`"[lightinthebox]"` → 目標:`"lightinthebox"`(移除首尾中括號)
| 方法 | 代碼 | 語義 | 靈活性 | 推薦度 |
|---|---|---|---|---|
| slice | `str.slice(1, -1)` | 切片:索引 1 到倒數第 1(不含) | 固定長度 | ⭐⭐⭐⭐⭐ |
| substring | `str.substring(1, str.length - 1)` | 子串:索引 1 到 length-1 | 固定長度 | ⭐⭐⭐⭐ |
| substr | `str.substr(1, str.length - 2)` | 從 1 開始取 length-2 字符 | 固定長度 | ⭐⭐(已棄用) |
| replace + 正則 | `str.replace(/^\[|\]$/g, '')` | 移除首尾特定字符 | 動態字符集 | ⭐⭐⭐⭐ |
| trim (ES2019+) | `str.trimStart()` / `trimEnd()` | 移除首尾空白 | 僅空白字符 | ⭐⭐⭐⭐⭐ |
| 自定義 trimChars | `str.trimChars('[]')` | 移除首尾指定字符集 | 完全可控 | ⭐⭐⭐⭐ |
const str = '[lightinthebox]';
// ✅ 最簡潔:slice 支援負索引
console.log(str.slice(1, -1)); // "lightinthebox"
// ✅ 兼容無負索引環境
console.log(str.substring(1, str.length - 1));
// ✅ 移除首尾空白(標準)
' hello '.trim(); // "hello"
' hello '.trimStart(); // "hello "
' hello '.trimEnd(); // " hello"
// ✅ 移除首尾指定字符集(通用 polyfill)
String.prototype.trimChars = function(chars = '\\s') {
const escaped = chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(`^[${escaped}]+|[${escaped}]+$`, 'g');
return this.replace(regex, '');
};
console.log('[[hello]]'.trimChars('[]')); // "hello"
console.log(' hello '.trimChars()); // "hello" (默認空白)
// ✅ 正則替換(單次操作移除首尾不同字符)
const s = '{hello}';
console.log(s.replace(/^\{|\}$/g, '')); // "hello"
// ⚠️ 原文寫法:substr(1).substring(-1,0) — 含義不明、依賴非標準行為,不推薦
需求:個位數補零,如 `9` → `09`
// 通用補零函數
const pad = (num, len = 2, char = '0') => String(num).padStart(len, char);
// 原文技巧:統一加前綴再取尾部
const formatTime = (h, m, s) =>
[h, m, s].map(v => ('0' + v).slice(-2)).join(':'); // "09:05:03"
console.log(formatTime(9, 5, 3)); // "09:05:03"
// 現代 ES2017 padStart
console.log(String(9).padStart(2, '0')); // "09"
const s = '[abcdefghijklmnopqrstuvwxyz]';
const N = 1e7;
console.time('slice(1,-1)');
for (let i=0;i
**固定長度首尾截取用 `slice(1, -1)` 最優**;需動態字符集用正則或 `trimChars`;時間補零用 `padStart`。拋棄 `substr`,避免原文 `substr(1).substring(-1,0)` 這類難以維護的鏈式調用。