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

如何用JavaScript统计单词数并实现按指定X个单词截取文本?

嘿,作为JS新手能想到优化文本截取的思路真不错!针对你想按指定单词数截取文本、同时统计单词数的需求,我给你整理几个简单好上手的实现方法:

按指定单词数截取文本的实现

方法一:基础版(适合常规文本)

这个方法逻辑直观,适合大多数没有特殊格式的文本:

  • 先把文本按空格分割成单词数组
  • 通过数组长度直接得到单词总数
  • 单词数超过限制时,截取前X个单词再拼接回字符串

代码示例:

function truncateByWordCount(text, wordLimit) {
  // 按空格分割成单词数组
  const words = text.split(' ');
  const totalWords = words.length;

  if (totalWords <= wordLimit) {
    // 单词数没超,直接返回原文本
    return `<p class='review-text'>${text}</p>`;
  } else {
    // 截取前wordLimit个单词,加上"read more"
    const truncatedText = words.slice(0, wordLimit).join(' ') + ' read more';
    return `<p class='review-text'>${truncatedText}</p>`;
  }
}

// 使用方式(替换你原来的代码)
const processedReview = truncateByWordCount(reviews[i].text, 10); // 这里按10个单词截取

方法二:优化版(处理特殊空白字符)

如果你的文本里有连续空格、制表符这类情况,基础版会生成空元素,用正则分割+过滤空内容就能解决:

function truncateByWordCount(text, wordLimit) {
  // 用正则匹配任意空白字符分割,同时过滤空字符串
  const words = text.split(/\s+/).filter(word => word.length > 0);
  const totalWords = words.length;

  if (totalWords <= wordLimit) {
    return `<p class='review-text'>${text}</p>`;
  } else {
    const truncatedText = words.slice(0, wordLimit).join(' ') + ' read more';
    return `<p class='review-text'>${truncatedText}</p>`;
  }
}

单独统计单词数的函数

如果需要单独统计文本的单词数量,用同样的正则思路就能实现:

function countTotalWords(text) {
  const words = text.split(/\s+/).filter(word => word.length > 0);
  return words.length;
}

// 使用示例
const reviewWordCount = countTotalWords(reviews[i].text);
console.log(`这篇评论共有${reviewWordCount}个单词`);

小提示

如果你的文本里有和单词连在一起的标点(比如"hello!"),需要把标点和单词分开统计的话,可以调整分割正则,比如用split(/[\s,.!?;:]+/),具体规则可以根据你的实际需求调整~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:11:13