萬盛學電腦網

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

JavaScript 字符串截取大全:substring/substr/slice 與中文截取方案

三大原生方法對比

方法語法參數含義負數處理推薦度
slicestr.slice(start, end)開始索引、結束索引(不含)負數 = length + 負數(從末尾算)⭐⭐⭐⭐⭐ 統一行為、支持負數、ES 標準
substringstr.substring(start, end)開始索引、結束索引(不含)負數視為 0;start>end 自動交換⭐⭐⭐ 歷史包袱、行為怪異
substrstr.substr(start, length)開始索引、長度start 負數 = length+start;length 負數 = 0⭐⭐ 非標準(附錄 B),不推薦新代碼使用

示例對比

const str = '0123456789';
str.slice(2, 5);     // '234'
str.substring(2, 5); // '234'
str.substr(2, 3);    // '234'

str.slice(-3);       // '789' (倒數3個)
str.substring(-3);   // '0123456789' (負數當0)
str.substr(-3);      // '789'

str.slice(5, 2);     // '' (空)
str.substring(5, 2); // '234' (自動交換)
str.substr(5, -2);   // '' (長度負數=0)

中文截取難點:雙字節字符

中文/日文/韓文/Emoji 佔 2~4 字節,直接按字符數截取會導致半個漢字(亂碼)或長度不準。

方案一:按字節長度截取(傳統 GBK/UTF-8 兼容)

function subByByte(str, maxBytes, suffix = '...') {
  let bytes = 0, len = 0;
  for (let i = 0; i < str.length; i++) {
    const code = str.charCodeAt(i);
    bytes += (code <= 0x7f) ? 1 : (code <= 0x7ff ? 2 : (code <= 0xffff ? 3 : 4)); // UTF-8 字節數
    if (bytes > maxBytes) break;
    len = i + 1;
  }
  return str.slice(0, len) + (len < str.length ? suffix : '');
}

// 測試
subByByte('你好ab', 6); // '你好ab' (中文3字節*2 + 英文1*2 = 8? 依編碼而定,建議用下方字符數方案)

字節長度依賴編碼,前端難以精確控制,**強烈建議改用字符數截取**。

方案二:按字符數截取(現代推薦,支持 Emoji)

function subByChar(str, maxChars, suffix = '...') {
  // 使用 Array.from 或展開運算符正確處理代理對
  const chars = [...str]; // 或 Array.from(str)
  if (chars.length <= maxChars) return str;
  return chars.slice(0, maxChars).join('') + suffix;
}

// 測試
subByChar('你好😀ab', 4); // '你好😀...' (emoji 算 1 字符)

方案三:Canvas 測量像素寬度截取(精確佈局)

function subByWidth(str, maxWidth, font = '14px Arial', suffix = '...') {
  const ctx = document.createElement('canvas').getContext('2d');
  ctx.font = font;
  if (ctx.measureText(str).width <= maxWidth) return str;
  let lo = 0, hi = str.length;
  while (lo < hi) {
    const mid = (lo + hi + 1) >> 1;
    if (ctx.measureText(str.slice(0, mid)).width <= maxWidth) lo = mid;
    else hi = mid - 1;
  }
  return str.slice(0, lo) + suffix;
}

擴展:String.prototype 原型掛載(慎用)

String.prototype.truncate = function(max, options = {}) {
  const { by = 'char', suffix = '...', font } = options;
  if (by === 'char') return subByChar(this, max, suffix);
  if (by === 'width') return subByWidth(this, max, font, suffix);
  // by === 'byte' ...
  return this;
};

'你好世界'.truncate(2); // '你...'
'Hello World'.truncate(10, { by: 'width', font: '16px Microsoft YaHei' });

常見場景封裝

// 多行文本截取(CSS 方案優先)
// CSS: display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden;

// 單行尾部省略(CSS)
// .ellipsis { white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }

// JS 兜底:多行文本按行截取
function clampLines(text, maxLines, lineHeight, font) {
  const ctx = document.createElement('canvas').getContext('2d');
  ctx.font = font;
  const words = [...text]; // 逐字符
  let lines = 1, current = '';
  for (const ch of words) {
    const test = current + ch;
    if (ctx.measureText(test).width > maxWidth) {
      lines++;
      if (lines > maxLines) return current + '...';
      current = ch;
    } else current = test;
  }
  return current;
}

總結

  • **首選 slice** 進行字符級截取,語義清晰、行為標準。
  • 中文/Emoji 截取用 [...str].slice(0, n).join('') 保證字符完整。
  • UI 截斷優先用 CSS text-overflow:ellipsis / -webkit-line-clamp,性能最好、自動響應縮放。
  • 需精確像素控制時用 Canvas measureText 二分查找。
  • 避免使用 substr、substring 的負數/交換特性,減少認知負擔。
copyright © 萬盛學電腦網 all rights reserved