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

如何修改按字符数分割文本的JS函数,为拆分单词添加连字符?

解决方案

要实现行尾拆分单词时添加连字符的逻辑,你需要在换行前判断当前是否截断了单词,若是则追加连字符。以下是修改后的完整代码:

var text = `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.`

function divideTextByLetterCount(text, letterCount) {
  let dividedText = "";
  let currentLetterCount = 0;
  for (let i = 0; i < text.length; i++) {
    dividedText += text[i];
    currentLetterCount++;
    if (currentLetterCount === letterCount) {
      // 判断是否截断了单词:下一个字符不是空格,且当前最后一个字符不是空格
      const isWordTruncated = i + 1 < text.length && text[i+1] !== ' ' && text[i] !== ' ';
      if (dividedText.slice(-1) === ' ') {
        dividedText = dividedText.slice(0, -1);
      }
      // 如果截断了单词,添加连字符
      if (isWordTruncated) {
        dividedText += '-';
      }
      dividedText += "\n";
      currentLetterCount = 0;
    }
  }
  let dividedTextArr = dividedText.split('\n');
  dividedTextArr.forEach((val, i) => {
    if (val.slice(0, 1) === ' ') {
      dividedTextArr[i] = val.slice(1);
    }
  });
  return dividedTextArr.join('\n');
}

console.log(divideTextByLetterCount(text, 20));

修改说明

  • 添加isWordTruncated判断:检查当前字符的下一个字符是否不是空格(说明当前行末尾的单词未结束),同时当前行最后一个字符也不是空格(排除刚好在空格处换行的情况)。
  • 若判定为单词被截断,就在换行前追加连字符-。

修改后的输出示例(部分):

Lorem Ipsum is simpl-
y dummy text of the
printing and typeset-
ting industry. Lorem
...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:15:26