如何在不拆分单词的前提下将数组长元素拆分为两个元素
解决数组中长字符串按单词拆分并插入原位置的问题
需求说明
给定一个包含不同长度对话字符串的数组,需要将长度超过200字符的元素拆分为两个独立元素,拆分时不能截断单词(必须基于空格拆分),并且要在原数组的正确位置插入拆分后的后半部分,替换原长元素为前半部分。
示例
输入数组:
[ "Hello there I'm shorter than 200 characters so do nothing with me", "I'm longer than 200 characters though so I should be split into two consecutive elements so that my first half stays where I am currently located in the array and my second half goes to the very next position in the array.", "I'm shorter than 200 so I just stay here as the last element." ]
期望输出:
[ "Hello there I'm shorter than 200 characters so do nothing with me", "I'm longer than 200 characters though so I should be split into two consecutive elements so that my first", "half stays where I am currently located in the array and my second half goes to the very next position in the array.", "I'm shorter than 200 so I just stay here as the last element." ]
原代码的问题
你写的代码存在几个关键问题:
- 使用
forEach遍历原数组时直接修改数组(push),会导致遍历顺序混乱,而且新元素会被加到数组末尾,不是原元素的下一个位置 - 直接用
substring(0, element.length/2)拆分,会粗暴截断单词,不符合需求 - 没有移除原来的长元素,导致数组里会保留原长元素加上错误拆分的内容
正确实现代码
我们可以通过倒序遍历数组来避免索引混乱,同时找到合适的拆分位置:
const myArray = [ "Hello there I'm shorter than 200 characters so do nothing with me", "I'm longer than 200 characters though so I should be split into two consecutive elements so that my first half stays where I am currently located in the array and my second half goes to the very next position in the array.", "I'm shorter than 200 so I just stay here as the last element." ]; // 倒序遍历,避免修改数组时影响后续索引 for (let i = myArray.length - 1; i >= 0; i--) { const str = myArray[i]; if (str.length <= 200) continue; // 找到第一个不超过200字符的最后一个空格位置 let splitIndex = str.lastIndexOf(' ', 200); // 极端情况:如果前200字符里没有空格(比如超长单词),直接在200位置拆分 if (splitIndex === -1) splitIndex = 200; const firstPart = str.substring(0, splitIndex).trim(); const secondPart = str.substring(splitIndex).trim(); // 替换原元素为前半部分,然后在当前索引后插入后半部分 myArray.splice(i, 1, firstPart); myArray.splice(i + 1, 0, secondPart); } console.log(myArray);
代码解释
- 倒序遍历:从数组最后一个元素往前遍历,这样即使在当前索引后插入新元素,也不会影响还没遍历到的元素的索引
- 找拆分位置:用
lastIndexOf(' ', 200)找到200字符以内最后一个空格的位置,保证拆分后前半部分不超过200字符且不截断单词 - 处理极端情况:如果前200字符里没有空格(比如一个超长单词),直接在200位置拆分(虽然不符合理想情况,但避免程序出错)
- 替换与插入:用
splice方法先替换原长元素为前半部分,再在当前索引+1的位置插入后半部分,保证顺序正确
内容的提问来源于stack exchange,提问作者user44109
相关产品推荐
相关产品推荐

