wrapping text words in new line

后端 未结 8 870
眼角桃花
眼角桃花 2021-02-10 04:53

I\'m using the below code for wrapping long text, entered by users in a text area for commenting:

function addNewlines(comments) {
  var result = \'\';
  while (         


        
8条回答
  •  温柔的废话
    2021-02-10 05:21

    After looking for the perfect solution using regex and other implementations. I decided to right my own. It is not perfect however worked nice for my case, maybe it does not work properly when you have all your text in Upper case.

    function breakTextNicely(text, limit, breakpoints) {
    
      var parts = text.split(' ');
      var lines = [];
      text = parts[0];
      parts.shift();
    
      while (parts.length > 0) {
        var newText = `${text} ${parts[0]}`;
    
        if (newText.length > limit) {
          lines.push(`${text}\n`);
          breakpoints--;
    
          if (breakpoints === 0) {
            lines.push(parts.join(' '));
            break;
          } else {
          	text = parts[0];
    	  }
        } else {
          text = newText;
        }
    	  parts.shift();
      }
    
      if (lines.length === 0) {
        return text;
      } else {
        return lines.join('');
      }
    }
    
    var mytext = 'this is my long text that you can break into multiple line sizes';
    console.log( breakTextNicely(mytext, 20, 3) );

提交回复
热议问题