Advertisement
nextdrift

text to linestext

Feb 28th, 2014
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function getLinesText(text) {
  2.     var
  3.         countLines = 1,
  4.         maxLineLength = 10,
  5.         words = text.split(' ');
  6.  
  7.     var lineBuffer = '', lineLength = 0, lines = [];
  8.  
  9.     for (var w in words) {
  10.  
  11.         var word = words[w];
  12.  
  13.         if ( (lineLength+word.length+1) > maxLineLength ) { // 1 - пробел
  14.  
  15.             if( lineBuffer.length > 0 ) { lines.push(lineBuffer); }
  16.            
  17.             lineBuffer = word;
  18.             lineLength = word.length;
  19.  
  20.         } else {
  21.  
  22.             if (lineLength > 0) {
  23.                 lineLength += 1; lineBuffer += ' '; // добавляем пробел, если слово не первое
  24.             }
  25.  
  26.             lineLength += word.length;
  27.             lineBuffer += word;
  28.  
  29.         }
  30.  
  31.         // если это последнее слово, отправляем в буффер
  32.         if ( w == (words.length -1) ) { lines.push(lineBuffer) };
  33.  
  34.     }
  35.  
  36.     // находим самую длинную строку
  37.     var maxLineLength = 0, outText = '';
  38.  
  39.     for(var l in lines) {
  40.         var
  41.             line = lines[l],
  42.             len = line.length;
  43.  
  44.         if ( len > maxLineLength) {
  45.             maxLineLength = len;
  46.         }
  47.  
  48.         if ( l > 0 ) { outText += '<br>' };
  49.  
  50.         outText += line;
  51.  
  52.     }
  53.    
  54.     return {
  55.         countLines: lines.length,
  56.         maxLineLenght: maxLineLength,
  57.         text: outText
  58.     };
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement