Java Script to wrap text as a paragraph

Consider a HTML page, where you are displaying data in tabular format. If some of the column values contains more than 50 characters and you want to limit number of characters per line. This can be done using the following Java Script. Before the text value is displayed in the table cell, it should be wrapped with this Java Script method. It limits the number of characters in a line to be 30.

The return value of the following method should be placed in the table's cell.

function wraptext(text){
                 var textLength = text.length;
                 var tempText ="";
                 var x = 0;
                 var y = 30;
                 var z = y;
                 var t = textLength % y;
                 for(var i = 0 ; i < textLength; i++){

                       if(i == z){
                             tempText = tempText + text.substring(x,z)+"<br>";
                             x = x+y;
                             z = z+y;
                       }

                       if(z > textLength){
                             tempText = tempText + text.substring(x,textLength)+"<br>";
                             break;
                       }

                 }
                 return tempText;
}

Search