How to split sentence into blocks of fixed length without breaking words in JavaScript



We are required to write a JavaScript function that takes in a string that contains a paragraph's text as the first argument and a chunk size number as the second argument .

The function should do the following things −

  • break the string into chunks of length not more than the chunk size (second argument),

  • the breaking should only happen at whitespaces or sentence end (should not break a word).

For example − If the input string is −

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

Then the output should be −

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

Let us write the code for this function −

We will use a regular expression to match the specified number of characters. Once matched we will backtrack until we find either a whitespace or end of the string.

Example

The code for this will be −

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));

Output

And the output in the console will be −

[
   '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.'
]

Advertisements