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

按指定不同长度分割字符串的实现方法咨询

实现按指定长度序列分割字符串

嘿,这个需求其实很好解决,核心就是按给定的长度逐个截取原字符串的子串,同时跟踪当前截取的位置就行。先帮你理清楚细节:你给出的目标子串对应的长度其实和描述的数字有点小出入(比如第2个目标子串是em,长度是2而不是3),我先对应你要的最终子串修正了长度数组,直接上代码方案:

核心实现代码

const s = 'Lorem ipsum dolor sit amet';
// 对应你要的子串的正确长度数组
const targetLengths = [3, 2, 3, 1, 1, 5, 3, 1, 2, 1];
const splitResult = [];
let currentIndex = 0;

// 遍历每个目标长度,逐个截取
for (const length of targetLengths) {
    // 从当前索引开始,截取length个字符
    const substring = s.slice(currentIndex, currentIndex + length);
    splitResult.push(substring);
    // 更新当前索引,准备下一次截取
    currentIndex += length;
}

console.log(splitResult);
// 输出结果正好是你要的:["Lor", "em", "ips", "u", "m", "dolor", "sit", "a", "me", "t"]

代码解释

  • 用slice()方法来截取子串,它不会修改原字符串,参数是起始索引和结束索引(不包含),所以slice(currentIndex, currentIndex + length)正好能拿到长度为length的子串。
  • 用currentIndex变量跟踪当前截取到的位置,每次截取后把它加上当前长度,就能无缝衔接下一次截取。

容错优化(可选)

如果担心目标长度的总和超过原字符串的长度,或者某个长度过大导致截取到空字符串,可以加个简单的判断,确保截取不会越界:

const s = 'Lorem ipsum dolor sit amet';
const targetLengths = [3, 2, 3, 1, 1, 5, 3, 1, 2, 1, 10]; // 故意加一个超长度的项
const splitResult = [];
let currentIndex = 0;

for (const length of targetLengths) {
    // 计算结束索引,最多到字符串末尾
    const endIndex = Math.min(currentIndex + length, s.length);
    const substring = s.slice(currentIndex, endIndex);
    splitResult.push(substring);
    currentIndex = endIndex;
    // 如果已经截取到字符串末尾,提前退出循环
    if (currentIndex >= s.length) break;
}

console.log(splitResult);
// 输出:["Lor", "em", "ips", "u", "m", "dolor", "sit", "a", "me", "t"](后面的10长度项会被忽略)

这样不管目标长度数组怎么设置,都不会出现异常啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:02:05