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

如何在JS中提取字符串首尾各3个单词并拼接(跳过中间内容)

问题解决:提取字符串前3个和最后3个单词并拼接

需求说明

从给定字符串中提取前3个单词和最后3个单词,拼接成新字符串,跳过中间内容。示例:
原字符串:"I have something important to tell you guys"
处理后结果:"I have something tell you guys"

现有代码已实现前3个单词的提取,但不确定单词总数时,不知道如何获取最后3个单词,代码如下:

let myString = "I have something important to tell you guys";
let myArray = "I have something important to tell you guys";

myArray = myArray.split(' ')
let firstThreeWords = myArray[0] + " " + myArray[1] + " " + myArray[2];
let lastThreeWords = ... //not sure what to put here

console.log(firstThreeWords + lastThreeWords)

解决方案

利用数组的slice()方法可以轻松解决这个问题,slice()支持负数索引,直接从数组末尾取元素,无需提前知道数组长度:

  1. 提取最后3个单词:使用myArray.slice(-3),该方法会返回数组的最后3个元素(如果数组长度不足3,则返回全部元素)
  2. 优化拼接方式:用join(' ')代替手动拼接,避免空格遗漏或多余的问题
  3. 简化代码:去掉重复的字符串赋值,直接使用myString.split(' ')生成数组

完整优化代码

let myString = "I have something important to tell you guys";
let myArray = myString.split(' ');

// 提取前3个单词,用join拼接成字符串
let firstThreeWords = myArray.slice(0, 3).join(' ');
// 提取最后3个单词
let lastThreeWords = myArray.slice(-3).join(' ');

// 拼接时注意加空格,避免前后单词连在一起
console.log(`${firstThreeWords} ${lastThreeWords}`);

边界情况处理(可选)

如果字符串的单词总数少于6个(比如只有4个单词),按需求逻辑可以判断后调整输出,比如直接返回原字符串:

let myString = "Hello world this is";
let myArray = myString.split(' ');

let result;
if (myArray.length <= 3) {
  result = myString;
} else if (myArray.length <= 5) {
  // 单词数在4-5之间,直接取全部单词(因为前3加最后3会覆盖全部)
  result = myString;
} else {
  let firstThree = myArray.slice(0,3).join(' ');
  let lastThree = myArray.slice(-3).join(' ');
  result = `${firstThree} ${lastThree}`;
}

console.log(result);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:40:21