根据最大字符长度拆分字符串,但要考虑单词

Sve*_*567 3 javascript string

因此,在我的程序中,我可以接收各种长度的字符串并将它们发送出去以进行翻译。如果这些字符串具有一定的字符长度,我会收到错误,因此我想在此之前检查并拆分这些字符串(如果有必要)。但我不能只在单词中间分割字符串,单词本身也需要完整并考虑在内。

例如:

let str = "this is an input example of one sentence that contains a bit of words and must be split"
let splitStringArr = [];

// If string is larger than X (for testing make it 20) characters
if(str.length > 20) {
    // Split string sentence into smaller strings, keep words intact
    //...
    // example of result would be
    // splitStringArr = ['this is an input', 'example of one sentence' 'that contains...', '...']
    // instead of ['this is an input exa' 'mple of one senten' 'ce that contains...']
}
Run Code Online (Sandbox Code Playgroud)

但我不知道如何分割句子并仍然考虑句子的长度。

解决方案是否是迭代字符串,将每个单词添加到其中并每次检查它是否超过最大长度,否则启动一个新的数组索引,或者是否有更好/现有的方法?

Cod*_*iac 5

您可以使用匹配、前瞻和单词边界,|.+以注意末尾的字符串,该字符串小于末尾的最大长度

let str = "this is an input example of one sentence that contains a bit of words and must be split"

console.log(str.match(/\b[\w\s]{20,}?(?=\s)|.+$/g))
Run Code Online (Sandbox Code Playgroud)


And*_*ndy 5

这是一个使用的示例reduce

const str = "this is an input example of one sentence that contains a bit of words and must be split";

// Split up the string and use `reduce`
// to iterate over it
const temp = str.split(' ').reduce((acc, c) => {

  // Get the number of nested arrays
  const currIndex = acc.length - 1;

  // Join up the last array and get its length
  const currLen = acc[currIndex].join(' ').length;

  // If the length of that content and the new word
  // in the iteration exceeds 20 chars push the new
  // word to a new array
  if (currLen + c.length > 20) {
    acc.push([c]);

  // otherwise add it to the existing array
  } else {
    acc[currIndex].push(c);
  }

  return acc;

}, [[]]);

// Join up all the nested arrays
const out = temp.map(arr => arr.join(' '));

console.log(out);
Run Code Online (Sandbox Code Playgroud)