How to wrap a string into lines of width w in TypeScript

1 Answer

0 votes
/*
    This program wraps a string into lines of maximum width w.

    Method:
    - Split the input text into words using split().
    - Build each line until adding another word would exceed the width.
    - When the limit is reached, store the line and begin a new one.
    - Uses arrays and string operations for clear and efficient processing.
*/

function wrapText(text: string, w: number): string {
    const words: string[] = text.split(/\s+/);   // Split on whitespace
    let line: string = "";
    const result: string[] = [];

    for (const word of words) {
        const currentWord: string = word;

        // If line is empty, start it with the word
        if (line.length === 0) {
            line = currentWord;
        }
        else {
            // Check if adding the next word exceeds width
            if (line.length + 1 + currentWord.length <= w) {
                line += " " + currentWord;
            } else {
                // Store the completed line
                result.push(line);
                line = currentWord;
            }
        }
    }

    // Add the final line
    if (line.length > 0) {
        result.push(line);
    }

    return result.join("\n");
}

// Usage
const sample: string =
    "TypeScript provides useful built-in tools for handling strings. " +
    "This program demonstrates how to wrap text cleanly and efficiently.";

const wrapped: string = wrapText(sample, 35);
console.log(wrapped);



/*
run:

TypeScript provides useful built-in
tools for handling strings. This
program demonstrates how to wrap
text cleanly and efficiently.

*/

 



answered 3 hours ago by avibootz
...