萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 移除字串首尾字符的多種方法與最佳實踐

場景

字串:`"[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"

效能實測(1000 萬次)

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)` 這類難以維護的鏈式調用。

copyright © 萬盛學電腦網 all rights reserved