Word wrapping is a complex topic. Typically, you wrap on word breaks (spaces) or max characters per line.
Here are some sample mixins that I use. wordWrap, wordWrappIntoArray, trim, ltrim, rtrim.
The original wordWrap code came from the Philips RSS module back in 2008. I don't think I enhanced it at all. I did put in documentation as comments below.
All these use regular expressions where /\S*$/ matches on characters. I leave it to you to google and go to a regular expression site to determine what they do.
//******************************************************************************** // JavaScript String Extensions //******************************************************************************** // String extensions for wordwrap + trimming //String.wordWrap(maxLength: Integer, [breakWith: String = "\n"], [cutWords: Boolean = false]): String //Returns an string with the extra characters/words "broken". //maxLengthmaximum amount of characters per line //breakWithstring that will be added whenever it's needed to break the line //cutWordsif true, the words will be cut, so the line will have exactly "maxLength" characters, otherwise the words won't be cut // if (!String.prototype.wordWrap) { String.prototype.wordWrap = function wordWrap(m, b, c) { var i, j, s, r = this.split("\n"); if (m > 0) { for (i in r) { for (s = r[i], r[i] = ""; s.length > m; j = c ? m : (j = s.substr(0, m).match(/\S*$/)).input.length - j[0].length || m, r[i] += s.substr(0, j) + ((s = s.substr(j)).length ? b : "")) {}; r[i] += s; } } return r.join("\n"); }; }
if (!String.prototype.wordWrapIntoArray) { String.prototype.wordWrapIntoArray = function wordWrapIntoArray(m, b, c) { var i, j, s, r = this.split("\n"); if (m > 0) { for (i in r) { for (s = r[i], r[i] = ""; s.length > m; j = c ? m : (j = s.substr(0, m).match(/\S*$/)).input.length - j[0].length || m, r[i] += s.substr(0, j) + ((s = s.substr(j)).length ? b : "")) {}; r[i] += s; } } return r; }; }
if (!String.prototype.trim) String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
if (!String.prototype.ltrim) String.prototype.ltrim = function() { return this.replace(/^\s+/, ""); };