JavaScript

  1. Home
  2. Computing & Technology
  3. JavaScript

Split Text Line Function

clr gif
Join the Discussion

Questions? Comments?

Related Resources

Cryptogram

When you are manipulating text using javascript you may have want to break that text up into multiple lines. The problem is that you can't just split text at regular intervals or you will end up with most lines ending right in the middle of words.

The following function will solve this for you. Simply pass in the text string and how long your maximum line length is. The function takes into account both spaces and line breaks (\n) when splitting the text and will return the text with no line being longer than the length you specified.

It is a simple matter to use this script for providing fixed width content to a web page. The following example code provides a maximum line length of 40 and also substitutes an HTML line break for every new line character in the returned text.

var myText40 = splitLine(myText,40);
var myHTML = myText40.replace(/\n/g,'<br \/>');

By using that code the original content of myText now displays on the web page in lines that contain no more than 40 characters and which do not have any words that are split between different lines (unless some of your content is too long to fit on one line.

Explore JavaScript

About.com Special Features

JavaScript

  1. Home
  2. Computing & Technology
  3. JavaScript
  4. Script Library
  5. Function Library
  6. Split Text Line Function

©2009 About.com, a part of The New York Times Company.

All rights reserved.