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

如何实现文本拆分为不截断单词、单元素最多125字符的数组

文本拆分函数实现

核心实现逻辑

要满足拆分要求,只需遵循以下核心规则:

  • 单段最大长度严格不超过125字符
  • 以空格作为单词拆分边界,禁止截断单个单词
  • 若125字符截取点落在单词内部,回退到该单词前的最后一个空格作为拆分点

完整代码实现(JavaScript)

function splitTextByMaxLength(text, maxLength = 125) {
  const result = [];
  let startIndex = 0;
  const textLength = text.length;

  while (startIndex < textLength) {
    // 截取当前起始位置后最大长度的子串
    let endIndex = startIndex + maxLength;
    // 已经到文本末尾,直接截取剩余部分
    if (endIndex >= textLength) {
      result.push(text.slice(startIndex));
      break;
    }
    // 查找当前子串中最后一个空格的位置
    let lastSpaceIndex = text.lastIndexOf(' ', endIndex);
    // 兜底处理:如果单个单词长度超过125,直接截断避免死循环
    if (lastSpaceIndex <= startIndex) {
      lastSpaceIndex = endIndex;
    }
    // 截取当前段
    result.push(text.slice(startIndex, lastSpaceIndex));
    // 更新起始位置到空格位置,下一段从空格后开始
    startIndex = lastSpaceIndex;
  }
  return result;
}

调用示例

你可以直接传入目标文本调用:

var text = " Lorem Ipsum is simply a text simulation of the printing and printing industry, and has been in use since the 16th century, when an unknown printer took a tray of typefaces and shuffled them together to make a type model book Lorem Ipsum survived not only five centuries but also the leap into desktop publishing, remaining essentially unchanged It became popular in the 1960s when Letraset launched decals containing passages of Lorem Ipsum, and more recently when is now integrated with desktop editing software like Aldus PageMaker."
const splitResult = splitTextByMaxLength(text);
console.log(splitResult);

说明

  • 代码默认最大长度为125,你也可以传入第二个参数自定义最大长度
  • 加入了超长单词的兜底逻辑,若存在单个单词长度超过125的极端情况,会直接截断该单词,避免程序进入死循环
  • 保留原文本的所有空格、标点符号格式,不会修改原文本内容

内容的提问来源于stack exchange,提问作者Hyago Lopes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:06:00