You may want to think of breaking lines on spaces, or hyphenating long words.
This method can take up to 3 arguments.
The first is the maximum line length,
the second is the minimum length of a hyphenated word,
the third is a switch for the line break string.
elem.innerHTML= s.wrap(20, 10, true);
String.prototype.wrap= function(n, hyphen, br){
var str1, tem, ax, diff, lim, S= [];
var A= this.split(/\\s*\
/);
n= n || 50;
hyphen= hyphen || n*2;
hyphen= Math.floor(hyphen/2);
while(A.length){
str1= A.shift();
while(str1 && str1.length> n){
if(ax=== 0 && /^\\S/.test(str1)) S[S.length-1]+= '-';
tem= str1.substring(0, n);
ax= tem.lastIndexOf(' ')+ 1;
if(ax== 0){
S.push(str1.substring(0, n-1));
str1= str1.substring(n-1);
}
else{
tem= str1.substring(0, ax);
diff= n-ax;
if(diff> hyphen){
lim=ax+ hyphen;
while(ax<lim && /\\w/.test(str1.charAt(ax))) ++ax;
tem= str1.substring(0, ax)+'-';
}
str1= str1.substring(ax);
S.push(tem);
}
}
if(str1) S.push(str1);
}
br= br? '<br>\
': '\
';
return S.join(br);
}
//test:
var s= “This is a test of the American Broadcast System. This is only a test, and not an actual emergency situation. If it was an actual emergency situation, we wouldn’t have said it was only a test.”;
s.wrap(20) returns>>
This is a test of
the American
Broadcast System.
This is only a
test, and not an
actual emergency
situation. If it
was an actual
emergency
situation, we
wouldn’t have said
it was only a test.
s.wrap(20,10,true) returns>>
This is a test of <br>
the American Broad-<br>
cast System. This <br>
is only a test, and <br>
not an actual emerg-<br>
ency situation. If <br>
it was an actual <br>
emergency situa-<br>
tion, we wouldn’t <br>
have said it was <br>
only a test.