tina tina - 1 year ago 79
Javascript Question

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download