首页 > 解决方案 > 如何将字符串分成小于定义长度的部分

问题描述

我有一个字符串 ( this is the very very very very long string),我想要将它分成少于 25 个字符的部分,并且这些部分必须有完整的单词,例如: this is the very very very very long string不是this is the very very verand y very long string

标签: javascript

解决方案


连接和收集这些部分并确实限制每个部分的连接长度的reduce基于方法可以实现类似于下一个提供的示例代码......

function concatAndCollectPartialsOfLimitedLength(collector, str) {
  const { limit = 24, list } = collector;

  const lastIdx = list.length - 1;
  const partial = list[lastIdx];

  if (partial && (partial.length + str.length + 1 <= limit)) {
    // concatenate if partial exists and if the length of its
    // next concatenated version does not exceed the limit ...

    list[lastIdx] = [partial, str].join(' ');
  } else {
    // ... otherwise provide and collect the base
    // for the following concatenation step(s).

    list.push(str);
  }
  return collector;
}

console.log(
  'concatenated partial length is limited to 24 chars ...',
  "this is the very very very very long string and some more of it and even more"
    .trim()
    .split(/\s+/)
    .reduce(concatAndCollectPartialsOfLimitedLength, { list: [] })
    .list
);
console.log(
  'concatenated partial length is limited to 13 chars ...',
  "this is the very very very very long string and some more of it and even more"
    .trim()
    .split(/\s+/)
    .reduce(
      concatAndCollectPartialsOfLimitedLength,
      { limit: 13, list: [] }
    )
    .list
);
console.log(
  'concatenated partial length is limited to 31 chars ...',
  "this is the very very very very long string and some more of it and even more"
    .trim()
    .split(/\s+/)
    .reduce(
      concatAndCollectPartialsOfLimitedLength,
      { limit: 31, list: [] }
    )
    .list
);
.as-console-wrapper { min-height: 100%!important; top: 0; }


推荐阅读