word_wrap.js 598 B

12345678910111213141516171819202122
  1. 'use strict';
  2. // https://github.com/rails/rails/blob/v4.2.0/actionview/lib/action_view/helpers/text_helper.rb#L240
  3. function wordWrap(str, options = {}) {
  4. if (typeof str !== 'string') throw new TypeError('str must be a string!');
  5. const width = options.width || 80;
  6. const regex = new RegExp(`(.{1,${width}})(\\s+|$)`, 'g');
  7. const lines = str.split('\n');
  8. for (let i = 0, len = lines.length; i < len; i++) {
  9. const line = lines[i];
  10. if (line.length > width) {
  11. lines[i] = line.replace(regex, '$1\n').trim();
  12. }
  13. }
  14. return lines.join('\n');
  15. }
  16. module.exports = wordWrap;