Advertisement
stuppid_bot

wordwrap javascript

Jul 11th, 2014
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // wrap(text[, width=78[, br='\n']])
  2. // Работает так же как wordwrap в PHP.
  3. // @author Сирожа <tz4678@gmail.com>
  4. function wrap(text, width, br) {
  5.     var lines, i, re, line, buf, matches, whitespace, word;
  6.     width = arguments.length > 1 ? arguments[1] : 78;
  7.     br = arguments.length > 2 ? arguments[2] : '\n';
  8.     lines = text.split('\n');
  9.     for (i = 0; i < lines.length; ++i) {
  10.         re = /(\s*)(\S+)/g;
  11.         line = [];
  12.         buf = '';
  13.         while (matches = re.exec(lines[i])) {
  14.             whitespace = matches[1];
  15.             word = matches[2];
  16.             if (buf.length + whitespace.length + word.length <= width) {
  17.                 buf += whitespace;
  18.             }
  19.             else {
  20.                 line.push(buf);
  21.                 buf = '';
  22.             }
  23.             buf += word;
  24.         }
  25.         line.push(buf);
  26.         lines[i] = line.join(br);
  27.     }
  28.     return lines.join('\n');
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement