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

In JavaScript, splitting a sentence into blocks of fixed length while keeping words intact requires careful handling of word boundaries. This ensures readability by avoiding broken words across blocks.

Understanding the Problem

We need to split a sentence into chunks of a specified maximum length without breaking words. Each block should contain complete words only, and if adding a word would exceed the length limit, that word starts a new block.

For example, with the sentence "You are reading this article on Tutorials point website" and block length 15, the output should be:

['You are reading', 'this article on', 'Tutorials point', 'website']

Algorithm Approach

The solution involves splitting the sentence into words, then grouping words into blocks while respecting the length constraint:

  1. Split the sentence into individual words
  2. Initialize an empty array for blocks and a current block string
  3. For each word, check if adding it exceeds the block length
  4. If it fits, add to current block; otherwise, start a new block
  5. Handle the final block after processing all words

Implementation

function splitSentence(sentence, blockLength) {
   const words = sentence.split(' ');
   const blocks = [];
   let currentBlock = '';

   for (let i = 0; i < words.length; i++) {
      const word = words[i];
      // Check if adding this word would exceed block length
      const potentialLength = currentBlock.length + (currentBlock ? 1 : 0) + word.length;
      
      if (potentialLength <= blockLength) {
         // Add word to current block
         currentBlock += (currentBlock.length > 0 ? ' ' : '') + word;
      } else {
         // Current block is full, start new one
         if (currentBlock) blocks.push(currentBlock);
         currentBlock = word;
      }
   }
   
   // Don't forget the last block
   if (currentBlock.length > 0) {
      blocks.push(currentBlock);
   }

   return blocks;
}

// Test the function
const sentence = "This is a sentence that has to be splitted into blocks of a fixed length";
const blockLength = 15;

const result = splitSentence(sentence, blockLength);
console.log("Original sentence:", sentence);
console.log("Block length:", blockLength);
console.log("Result blocks:", result);

// Verify block lengths
result.forEach((block, index) => {
   console.log(`Block ${index + 1} (length ${block.length}): "${block}"`);
});
Original sentence: This is a sentence that has to be splitted into blocks of a fixed length
Block length: 15
Result blocks: [
  'This is a',
  'sentence that',
  'has to be',
  'splitted into',
  'blocks of a',
  'fixed length'
]
Block 1 (length 9): "This is a"
Block 2 (length 13): "sentence that"
Block 3 (length 9): "has to be"
Block 4 (length 13): "splitted into"
Block 5 (length 11): "blocks of a"
Block 6 (length 12): "fixed length"

Enhanced Version with Edge Cases

Here's an improved version that handles edge cases like empty strings and words longer than the block length:

function splitSentenceAdvanced(sentence, blockLength) {
   if (!sentence || blockLength <= 0) return [];
   
   const words = sentence.split(' ').filter(word => word.length > 0);
   if (words.length === 0) return [];
   
   const blocks = [];
   let currentBlock = '';

   for (const word of words) {
      // Handle words longer than block length
      if (word.length > blockLength) {
         if (currentBlock) {
            blocks.push(currentBlock);
            currentBlock = '';
         }
         blocks.push(word); // Add long word as separate block
         continue;
      }
      
      const spaceNeeded = currentBlock ? 1 : 0;
      
      if (currentBlock.length + spaceNeeded + word.length <= blockLength) {
         currentBlock += (currentBlock ? ' ' : '') + word;
      } else {
         blocks.push(currentBlock);
         currentBlock = word;
      }
   }
   
   if (currentBlock) blocks.push(currentBlock);
   return blocks;
}

// Test with edge cases
console.log("Empty string:", splitSentenceAdvanced("", 10));
console.log("Single word:", splitSentenceAdvanced("Hello", 10));
console.log("Long word:", splitSentenceAdvanced("Supercalifragilisticexpialidocious world", 10));
Empty string: []
Single word: [ 'Hello' ]
Long word: [ 'Supercalifragilisticexpialidocious', 'world' ]

Complexity Analysis

Time Complexity: O(n), where n is the number of characters in the sentence. We process each word once.

Space Complexity: O(n + b), where n is the input size and b is the number of blocks created.

Key Points

  • Always preserve complete words - never break them across blocks
  • Handle edge cases like empty strings and oversized words
  • Consider space characters when calculating block lengths
  • The last block might be shorter than the specified length

Conclusion

This solution efficiently splits sentences into fixed-length blocks while maintaining word integrity. The algorithm ensures readability by avoiding broken words and handles various edge cases gracefully.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements