wrapping text words in new line

后端 未结 8 722
眼角桃花
眼角桃花 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:04

    I believe wrapping a text by CSS is a better solution however there is a link here which may be helpful wrap-text-in-javascript

    by the way i remember there is a JQuery plugin for wrapping text google it too.

    0 讨论(0)
  • 2021-02-10 05:12

    I use this css code for displaying in Torch browser and it works

    I've tried word-wrap:break-word;overflow:ellipsis;....etc, but didn't work.

    #xxx{
    
     width: 750px;
     word-break: break-word;
    
    }
    
    0 讨论(0)
  • 2021-02-10 05:14

    Try one of these:

    1. word-wrap:no-wrap;
    2. word-wrap: break-word

    It might solve your problem

    0 讨论(0)
  • 2021-02-10 05:15

    Hi just apply some css on text area like

    style="word-wrap: break-word;" 
    
    0 讨论(0)
  • 2021-02-10 05:17

    The ones above only work 99% of the time. This is the only one that works for me 100%: http://locutus.io/php/strings/wordwrap/

    0 讨论(0)
  • 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) );

    0 讨论(0)
提交回复
热议问题