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

标签 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...']
}

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

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

最佳答案

这是一个使用 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);

关于javascript - 根据最大字符长度拆分字符串,但要考虑单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58204155/

相关文章:

string - 使由 '{' 、 '}' 、 '[' 、 ']' 、 '(' 、 ')' 组成的括号字符串的最小加法有效

javascript将字符串中的空格转换为符号

javascript - 在 Angularjs 中保存、发送和检索数据

javascript - 选择文件后进行中

javascript - 在 JavaScript 中根据长度将字符串转换为一系列下划线

c++ - 部分字符串转换为整数 - C++

Python strip()unicode字符串?

javascript - 在jsp中成功提交表单后清除表单字段

java - JSF 2.0 在 FacesContext.responseComplete() 上执行 javascript

c# - 在c#中将代码列表集合写入字符串