| 方法 | 語法 | 參數含義 | 負數處理 | 推薦度 |
|---|---|---|---|---|
slice | str.slice(start, end) | 開始索引、結束索引(不含) | 負數 = length + 負數(從末尾算) | ⭐⭐⭐⭐⭐ 統一行為、支持負數、ES 標準 |
substring | str.substring(start, end) | 開始索引、結束索引(不含) | 負數視為 0;start>end 自動交換 | ⭐⭐⭐ 歷史包袱、行為怪異 |
substr | str.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 字節,直接按字符數截取會導致半個漢字(亂碼)或長度不準。
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? 依編碼而定,建議用下方字符數方案)
字節長度依賴編碼,前端難以精確控制,**強烈建議改用字符數截取**。
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 字符)
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.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** 進行字符級截取,語義清晰、行為標準。[...str].slice(0, n).join('') 保證字符完整。text-overflow:ellipsis / -webkit-line-clamp,性能最好、自動響應縮放。measureText 二分查找。substr、substring 的負數/交換特性,減少認知負擔。