How to force breaking of non breakable strings?

后端 未结 9 1051
-上瘾入骨i
-上瘾入骨i 2021-02-04 18:52

I have an HTML page that I generate from the data contained in a database. The database sometimes contains long strings that the browser can\'t break because the strings don\'t

9条回答
  •  一整个雨季
    2021-02-04 19:35

    It's easier to break up the long words from a text string, before you add them to the document.

    It would also be nice to avoid orphans, where you have only one or two characters on the last line.

    This method will insert spaces in every unspaced run of characters longer than n, splitting it so that there are at least min characters on the last line.

    function breakwords(text, n, min){
     var L= text.length;
     n= n || 20;
     min= min || 2;
     while(L%n && L%n

    //test

    var n=30, min=5;

    var txt= 'abcdefghijklmnopqrstuvwxyz0123456789 abcdefghijklmnopqrstuvwxyz012345678 abcdefghijklmnopqrstuvwxyz01234567 abcdefghijklmnopqrstuvwxyz0123456';

    txt=txt.replace(/(\w{30,})/g,function(w){return breakwords(w,n,min)});

    alert(txt.replace(/ +/g,'\n'))

    /*  returned value: (String)
    abcdefghijklmnopqrstuvwxyz0123
    456789
    abcdefghijklmnopqrstuvwxyz0123
    45678
    abcdefghijklmnopqrstuvwxyz012
    34567
    abcdefghijklmnopqrstuvwxyz01
    23456
    */
    

提交回复
热议问题