Word Wrap //JavaScript Repository

Description

Break the lines that exceed a certain amount of characters.
Created: 2005.11.06 - Modified 2007.10.06

Code (Download)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/string/wordwrap [rev. #2]

String.prototype.wordWrap = function(m, b, c){
    var i, j, l, s, r;
    if(m < 1)
        return this;
    for(i = -1, l = (r = this.split("\n")).length; ++i < l; r[i] += s)
        for(s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : ""))
            j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length
            || c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
    return r.join("\n");
};

Example (Example)

<script type="text/javascript">
//<![CDATA[

var s = "MY WORLD IS BIIIIIIIIIIIIIIIIIIIIIG!!!!!";
document.write(
    "<h2>S = ", s, "</h2>",
    "<h2>S.wordWrap(10, \"&lt;br/&gt;\", 0)</h2>", s.wordWrap(10, "<br/>", 0),
    "<h2>S.wordWrap(10, \"&lt;br/&gt;\", 1)</h2>", s.wordWrap(10, "<br/>", 1),
    "<h2>S.wordWrap(10, \"&lt;br/&gt;#\", 2)</h2>", s.wordWrap(10, "<br/>#", 2)
);

//]]>
</script>

Help

String.wordWrap(maxLength: Integer, [breakWith: String = "\n"], [cutType: Integer = 0]): String
Returns an string with the extra characters/words "broken".
maxLength
maximum amount of characters per line
breakWtih
string that will be added whenever it's needed to break the line
cutType
  • 0 = words longer than "maxLength" will not be broken
  • 1 = words will be broken when needed
  • 2 = any word that trespass the limit will be broken

Rank (Votes: 74)

4.31