![]() |
VOOZH | about |
Given a sentence, our task is to split it into blocks of a fixed length without breaking words using JavaScript.
Example:
Input:
Sentence= "This is a sample sentence to demonstrate splitting into blocks
without breaking words.", blocksize = 15
Output:
Blocks: [ 'This is a', 'sample sentence ', 'to demonstrate', 'splitting into', 'blocks without', 'breaking words.' ]
Below are the approaches to splitting sentences into blocks of a fixed length without breaking words in JavaScript:
Table of Content
In this approach, we use reduce to iterate through the words of the sentence, accumulating them into blocks of the specified length.
Example: The below code example uses reduce to split it into blocks of a fixed length without breaking words.
Blocks: [ 'This is a', 'sample sentence', 'to demonstrate', 'splitting into', 'blocks without', 'breaking words.' ]
Time complexity: O(n)
Auxiliary Space: O(n)
In this approach we first split the sentence into words, then use forEach to accumulate words into blocks
Example: The below code example is a practical implementation to split it into blocks of a fixed length without breaking words using split and forEach.
Blocks: [ 'This is another', 'example sentence to', 'show how to split it', 'into blocks of fixed', 'length.' ]
Time Complexity: O(n)
Auxiliary Space: O(n)
In this approach, we use a while loop to iterate through the words of the sentence, accumulating them into blocks of the specified length.
Example: The below code example uses a while loop to split the sentence into blocks of a fixed length without breaking words.
Blocks: [ 'This approach uses a', 'while loop to split the', 'sentence into blocks', 'without breaking words.' ]
Time Complexity: O(n)
Auxiliary Space: O(n)