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

前端如何根据字符串长度动态插入换行,将后端返回长文本拆分为段落?

实现方案
  • 第一步:使用正则匹配提取所有独立节内容,正则规则/\*\d+\*.*?(?=\*\d+\*|$)/g可以精准匹配每一个从*数字*开头、到下一个*数字*之前或者字符串结尾的内容,不会遗漏最后一节
  • 第二步:将提取到的节数组按每10个为一组拆分
  • 第三步:每组拼接为独立段落,组与组之间插入换行/HTML段落标签即可

可直接运行的JS实现代码

// 纯文本拆分版本
function splitTextIntoParagraphs(rawStr, groupSize = 10) {
  // 清除后端返回可能带的前后引号
  const cleanedStr = rawStr.replace(/^"|"$/g, '');
  // 匹配所有独立节
  const sectionReg = /\*\d+\*.*?(?=\*\d+\*|$)/g;
  const sections = cleanedStr.match(sectionReg) || [];
  // 不足10节直接返回原内容
  if (sections.length <= groupSize) return cleanedStr;
  // 按每组10个拆分
  const groups = [];
  for (let i = 0; i < sections.length; i += groupSize) {
    groups.push(sections.slice(i, i + groupSize).join(''));
  }
  // 组间加两个换行对应段落分隔,需要自定义分隔符可修改此处
  return groups.join('\n\n');
}

// HTML渲染版本
function splitTextIntoHtmlParagraphs(rawStr, groupSize = 10) {
  const cleanedStr = rawStr.replace(/^"|"$/g, '');
  const sections = cleanedStr.match(/\*\d+\*.*?(?=\*\d+\*|$)/g) || [];
  if (sections.length <= groupSize) return `<p>${cleanedStr}</p>`;
  const groups = [];
  for (let i = 0; i < sections.length; i += groupSize) {
    groups.push(`<p>${sections.slice(i, i + groupSize).join('')}</p>`);
  }
  return groups.join('');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:09:00