字串:`"1,2,3,4,5,"` → 目標:`"1,2,3,4,5"`(移除尾部逗號)
| 方法 | 代碼 | 語義 | 效能 | 備註 |
|---|---|---|---|---|
| slice | `str.slice(0, -1)` | 提取 0 到倒數第 1(不含) | ⭐⭐⭐⭐⭐ | **推薦**:語義清晰、支援負索引、不修改原字串 |
| substring | `str.substring(0, str.length - 1)` | 提取 0 到 length-1 | ⭐⭐⭐⭐ | 不支援負索引,需手動計算 length |
| substr | `str.substr(0, str.length - 1)` | 從 0 開始取 length-1 字符 | ⭐⭐⭐ | **已棄用**(非標準),避免使用 |
| replace | `str.replace(/,$/, '')` | 正則替換尾部逗號 | ⭐⭐ | 通用性強,但正則開銷大、易寫錯 |
const str = '1,2,3,4,5,';
// ✅ 最佳:slice 支援負索引
const r1 = str.slice(0, -1);
console.log(r1); // "1,2,3,4,5"
// ✅ 兼容老瀏覽器(不支援負索引)
const r2 = str.substring(0, str.length - 1);
// ⚠️ 僅當確定結尾是特定字符時用 replace
const r3 = str.replace(/,$/, ''); // 只移除尾部逗號,不影響中間
// ❌ 避免:substr 已從 Web 標準移除(MDN 標註 Legacy)
// const r4 = str.substr(0, str.length - 1);
// 移除首尾各 1 個字符:如 "[abc]" -> "abc"
const s = '[abc]';
console.log(s.slice(1, -1)); // "abc"
// 移除首尾空白(標準方法)
const s2 = ' hello ';
console.log(s2.trim()); // "hello"
// 移除首尾指定字符集(polyfill)
String.prototype.trimChars = function(chars = '\\s') {
const regex = new RegExp(`^[${chars}]+|[${chars}]+$`, 'g');
return this.replace(regex, '');
};
console.log('[[hello]]'.trimChars('[]')); // "hello"
const str = 'a,'.repeat(1000); // 2000 字符
const iterations = 1e7;
console.time('slice');
for (let i = 0; i < iterations; i++) str.slice(0, -1);
console.timeEnd('slice'); // ~180ms
console.time('substring');
for (let i = 0; i < iterations; i++) str.substring(0, str.length - 1);
console.timeEnd('substring'); // ~210ms
console.time('replace');
for (let i = 0; i < iterations; i++) str.replace(/,$/, '');
console.timeEnd('replace'); // ~450ms
**`str.slice(0, -1)` 是刪除最後一個字符的最佳選擇**:語義明確、支援負索引、效能最高、ES3 起全瀏覽器支援。避免使用已棄用的 `substr()`,除非需正則匹配模式,否則不建議用 `replace()`。