Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wrapping text words in new line

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 ($.trim(comments).length > 0) {

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

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

scrn shot of output

like image 771
tina Avatar asked Apr 22 '13 06:04

tina


People also ask

How do you wrap text in new line?

break-word: This is the actual CSS syntax that tells the browser to wrap a long text over to a new line. normal: It breaks each word at the normal points of separation within a DOM. It doesn't have effect on long strings. initial: It's the default browser's way of handling strings.

Why does my text wrap to the next line?

This happens if you accidentally change the paragraph indentation for the document. Ensure that Indentation, both before and after text, are set to zero and that no special formatting has been set.

How do you break span text?

You can use the CSS property word-wrap:break-word; , which will break words if they are too long for your span width.


2 Answers

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.

like image 79
Morteza Adi Avatar answered Sep 27 '22 20:09

Morteza Adi


Try word-wrap: break-word in CSS.
The word-wrap property is well supported by browsers (even IE 5.5+).
More info here: https://developer.mozilla.org/en-US/docs/CSS/word-wrap
Sample usage: FIDDLE

like image 22
Artyom Neustroev Avatar answered Sep 27 '22 20:09

Artyom Neustroev