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

JavaScript实现按字符数分组且保留完整单词的字符串拆分函数

实现splitSentence函数:按字符限制拆分完整单词组

要解决按字符数限制拆分完整单词的问题,我们可以通过遍历单词数组、逐步累加验证的方式实现,避免拆分单词。以下是具体的JavaScript实现:

function splitSentence(sentence, nChar) {
  const words = sentence.split(' ');
  const result = [];
  let currentGroup = [];
  let currentLength = 0;

  for (const word of words) {
    // 计算加入当前单词后的总长度:当前组长度 + 空格(非首单词时) + 当前单词长度
    const requiredLength = currentLength + (currentGroup.length > 0 ? 1 : 0) + word.length;
    
    if (requiredLength <= nChar) {
      currentGroup.push(word);
      currentLength = requiredLength;
    } else {
      // 当前组存入结果,开启新组
      if (currentGroup.length > 0) {
        result.push(currentGroup.join(' '));
      }
      currentGroup = [word];
      currentLength = word.length;
    }
  }

  // 加入最后一组未处理的内容
  if (currentGroup.length > 0) {
    result.push(currentGroup.join(' '));
  }

  return result;
}

// 测试示例
const testSentence = 'the quick cucumber fox jumps over the lazy dog.';
console.log(splitSentence(testSentence, 15));
// 输出:['the quick cucumber', 'fox jumps over', 'the lazy dog.']

核心逻辑说明

  • 将原句子按空格拆分为独立单词数组,确保操作单元是完整单词。
  • 用currentGroup暂存当前构建的单词组,currentLength记录当前组的总字符数(包含单词间的空格)。
  • 遍历每个单词时,计算加入当前组后的总长度:
    • 若总长度≤nChar,则将单词加入当前组并更新总长度。
    • 若总长度超过nChar,则将当前组存入结果数组,以当前单词为起点开启新组。
  • 遍历结束后,将最后一组未存入的单词组加入结果数组。

这个方案严格保证每个分组由完整单词组成,且每组字符数不超过指定的nChar限制,完全匹配需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 02:01:13