You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按指定最大字符长度对文本进行自动换行处理?

文本按指定最大长度拆分的JavaScript实现方案

需求明确:将一段文本拆分为每行最多包含N个字符的数组,若单个单词长度超过N则直接截断该单词。原代码无法正常工作,以下是修复方案。

原代码问题分析

  • str.substr(min, max) 参数误用:substr 第二个参数是截取长度而非结束索引,正确应为 max - min
  • 未处理「目标位置无空格」场景:当单词长度超过maxLen时,lastIndexOf会返回-1,导致逻辑崩溃
  • 循环结束后遗漏剩余文本:最后一段未加入结果数组

修复后的代码

const sentence =`Wake has three meanings as a noun, and, yes, just about as many meanings as a verb! So get set. To wake is come out of sleep, a verb you'll recognize from "Wake up! You're asleep at the wheel!" You can wake feelings, as well as the people who are having them. The wake before the funeral caused Mike to wake from his depression and decide to live life to the fullest. His first act was to water ski; he eventually mastered staying upright while crossing the wake of the boat that was towing him.`

// 按最大长度10拆分示例
console.log(shorten(sentence, 10));

function shorten(str, maxLen) {
  // 直接返回长度符合要求的文本
  if (str.length <= maxLen) return [str];
  
  const result = [];
  let start = 0;
  const strTotalLen = str.length;

  while (start < strTotalLen) {
    let end = start + maxLen;
    // 未到文本末尾时,优先按空格拆分
    if (end < strTotalLen) {
      let spaceIndex = str.lastIndexOf(' ', end);
      // 找不到空格(单词超长)则直接截断
      if (spaceIndex === -1 || spaceIndex < start) {
        spaceIndex = end;
      }
      end = spaceIndex;
    }
    // 截取当前行并去除首尾空格
    result.push(str.slice(start, end).trim());
    // 更新起始位置,跳过空格
    start = end + 1;
  }

  return result;
}

代码关键说明

  • 用slice替代substr,slice(start, end)更直观地表示截取范围
  • 兼容单词超长场景:目标范围内无空格时,直接在start + maxLen位置截断
  • 自动处理剩余文本:循环结束前会把最后一段内容加入结果
  • 用trim()清理每行首尾空格,避免空行或多余空格

示例输出(maxLen=10)

["Wake has", "three", "meanings", "as a noun,", "and, yes,", "just about", "as many", "meanings", "as a verb!", "So get set.", "To wake is", "come out of", "sleep, a", "verb you'll", "recognize", "from \"Wake", "up! You're", "asleep at", "the wheel!", "You can", "wake", "feelings, as", "well as the", "people who", "are having", "them. The", "wake before", "the funeral", "caused Mike", "to wake from", "his", "depression", "and decide", "to live life", "to the", "fullest. His", "first act", "was to", "water ski;", "he", "eventually", "mastered", "staying", "upright", "while", "crossing the", "wake of the", "boat that", "was towing", "him."]

内容的提问来源于stack exchange,提问作者Raol mAX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 23:07:49