如何在JavaScript中将句子拆分成固定长度的块而又不破坏单词

我们需要编写一个JavaScript函数,该函数接受一个字符串,该字符串包含段落的文本作为第一个参数,而块大小数字作为第二个参数。

该函数应执行以下操作-

  • 将字符串分成长度不超过块大小的块(第二个参数),

  • 中断只能发生在空格或句子结尾(不应中断一个单词)。

例如-如果输入字符串是-

const str = 'this is a string';
const chunkLength = 6;

那么输出应该是-

const output = ['this', 'is a', 'string'];

让我们为该函数编写代码-

我们将使用正则表达式来匹配指定数量的字符。一旦匹配,我们将回溯直到找到空格或字符串结尾。

示例

为此的代码将是-

const size = 200;
const str = "This process was continued for several years for the deaf
child does not here in a month or even in two or three years the
numberless items and expressions using the simplest daily intercourse
little hearing child learns from these constant rotation and imitation the
conversation he hears in his home simulates is mine and suggest topics and
called forth the spontaneous expression of his own thoughts.";
const splitString = (str = '', size) > {
   const regex = new RegExp(String.raw`\S.{1,${size &minu; 2}}\S(?= |$)`,
   'g');
   const chunks = str.match(regex);
   return chunks;
}
console.log(splitString(str, size));

输出结果

控制台中的输出将是-

[
   'This process was continued for several years for the deaf child does
   not here in a month or even in two or three years the numberless items and
   expressions using the simplest daily intercourse little',
   'hearing child learns from these constant rotation and imitation the
   conversation he hears in his home simulates is mine and suggest topics and
   called forth the spontaneous expression of his own',
   'thoughts.'
]