INNER CODE UNIT · JavaScript
smartTruncate
rockbenben/ChatGPT-Shortcut · plugin-gen-geo.js:91
function smartTruncate(text, maxLen) {
if (!text || text.length <= maxLen) return text;
const slice = text.slice(0, maxLen);
// 在 maxLen 的后 30% 范围内寻找句子边界,避免过度截断
const minBoundary = Math.floor(maxLen * 0.7);
const boundaries = [
/[。!?.!?][^。!?.!?]*$/, // 句末标点
/[;;][^;;]*$/, // 分号
/[,,][^,,]*$/, // 逗号
/\s\S*$/, // 空格
];
for (const re of boundaries) {
const match = slice.match(re);
if (match && match.index >= minBoundary) {
return slice.slice(0, match.index + 1);
}
}
return slice;