Javascript

Splitting a string into multiple lines in Javascript

“wordwrap” for JavaScript Another version: It takes three arguments: The string to be wrapped. The column width (a number, default: 75) The...

Written by Luci · 58 sec read >
“wordwrap” for JavaScript
<!DOCTYPE HTML>
<html>
  <body>
    	<div id="log" style="white-space: pre;"></div>
  </body>
</html>

 <script>
	function wordWrap(str, maxWidth) {
        const newLineStr = "\n";
        let done = false;
        let res = '';
        do {
            let found = false;
            // Inserts new line at first whitespace of the line
            for (let i = maxWidth - 1; i >= 0; i--) {
                if (this.whitespace(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);
            }

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

        return res + str;
    }

    function whitespace(string) {
        const white = new RegExp(/^\s$/);
        return white.test(string.charAt(0));
    }

    const result = wordWrap("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.", 20);
    console.log(result);

    document.getElementById("log").innerHTML = result;
</script>

Another version:

It takes three arguments:

  • The string to be wrapped.
  • The column width (a number, default: 75)
  • The character(s) to be inserted at every break. (default: ‘n’)

Use of regular expressions to remove the computationally heavy bits out of Javascript

function wordwrap( str, width, brk ) {
    brk = brk || 'n';
    width = width || 75;
 
    if (!str) { 
       return str; 
    }
 
    var regex = '.{1,' +width+ '}(\s|$)' + ('|\S+?(\s|$)');
 
    return str.match( RegExp(regex, 'g') ).join( brk );
}

Usage:

wordwrap('The quick brown fox jumped over the lazy dog.', 20, '<br/>n');
Written by Luci
I am a multidisciplinary designer and developer with a main focus on Digital Design and Branding, located in Cluj Napoca, Romania. Profile
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x