Wrap text words in a new line

I use the code below to wrap long text entered by users in the text area for comments:

function addNewlines(comments) {
  var result = '';
  while ($.trim(comments).length > 0) {

    result += comments.substring(0,70) + '\n';
    comments = comments.substring(70);
  }
  return result;
}

The problem is shown in the screenshot below. Any ideas on how to solve it? Can we use the method lastindexof(" ")to get the last space in a substring to solve this problem logically? Can someone tweak this little code to make it correct?

scrn shot of output

+5
source share
7 answers

I believe that wrapping text using CSS is the best solution, however there is a link here that might be useful wrap-text-in-javascript

By the way, I remember that there is a jQuery plugin for wrapping google text.

+1

:

  • word-wrap:no-wrap;
  • word-wrap: break-word

.

+1

word-wrap: break-word CSS.
word-wrap ( IE 5.5+).
: https://developer.mozilla.org/en-US/docs/CSS/word-wrap
: FIDDLE

+1
+1

, CSS ,

style="word-wrap: break-word;" 
0

css Torch

I tried word-wrap:break-word;overflow:ellipsis;.... etc, but did not work.

#xxx{

 width: 750px;
 word-break: break-word;

}
0
source

After finding the perfect solution using regular expressions and other implementations. I decided to fix my own. This is not perfect, but it worked well for my case, it may not work properly when you have all the text in the 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) );
Run code
0
source

All Articles