javascriptjqueryword-wrap

Wrap Text In JavaScript


I am new to JavaScript and jQuery.

I have a variable named as str in JavaScript and it contains very long text, saying something like

"A quick brown fox jumps over a lazy dog". 

I want to wrap it and assign it to the same variable str by inserting the proper \n or br/ 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 str 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...


Solution

  • 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 = '';
        while (str.length > maxWidth) {                 
            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;
                    break;
                }
            }
            // 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);
            }
    
        }
    
        return res + str;
    }
    
    function testWhite(x) {
        var white = new RegExp(/^\s$/);
        return white.test(x.charAt(0));
    };