user2004685 user2004685 - 2 months ago 8x
Javascript Question

Wrap Text In JavaScript

I am new to JavaScript and jQuery.

I have a variable named as

in JavaScript and it contains very long text say something like

“A quick brown fox jumps over a lazy dog”.

I want to wrap it and assign it to the same variable
by inserting the proper
tags at the correct places.

I don't want to use CSS etc. Could you please tell me how to do it with a proper function in JavaScript which takes the
and returns the proper formatted text to it?

Something like:

str = somefunction(str, maxchar);

I tried a lot but unfortunately nothing turned up the way I wanted it to be! :(

Any help will be much appreciated...


This should insert a line break at the nearest whitespace of maxChar:

str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It w as popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

str = wordWrap(str, 40);

function wordWrap(str, maxWidth) {
    var newLineStr = "\n"; done = false; res = '';
    do {                    
        found = false;
        // Inserts new line at first whitespace of the line
        for (i = maxWidth - 1; i >= 0; i--) {
            if (testWhite(str.charAt(i))) {
                res = res + [str.slice(0, i), newLineStr].join('');
                str = str.slice(i + 1);
                found = true;
        // Inserts new line at maxWidth position, the word is too long to wrap
        if (!found) {
            res += [str.slice(0, maxWidth), newLineStr].join('');
            str = str.slice(maxWidth);

        if (str.length < maxWidth)
            done = true;
    } while (!done);

    return res;

function testWhite(x) {
    var white = new RegExp(/^\s$/);
    return white.test(x.charAt(0));