Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,710 questions

55,474 answers

573 users

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

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, w) {
    const words = text.split(/\s+/);   // Split on whitespace
    let line = "";
    let result = "";

    for (const word of words) {

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

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

    return result;
}

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

console.log(wrapText(sample, 35));


/*
run:

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

*/

 



answered Jul 11 by avibootz
...