How to wrap long lines without spaces in HTML?

前端 未结 14 1880
旧巷少年郎
旧巷少年郎 2020-12-01 03:28

If a user types in a long line without any spaces or white space, it will break formating by going wider than the current element. Something like:

HA

14条回答
  •  粉色の甜心
    2020-12-01 04:07

    I didn't want to add libraries to my pages just for word breaking. Then I wrote a simple function which I provide below, hope it helps people.

    (It is breaking by 15 characters, and applying "& shy;" between, but you can change it easily in the code)

    //the function:
    BreakLargeWords = function (str)
    {
        BreakLargeWord = function (word)
        {
            var brokenWords = [];
            var wpatt = /\w{15}|\w/igm;
            while (wmatch = wpatt.exec(word))
            {
                var brokenWord = wmatch[0];
                brokenWords.push(brokenWord);
                if (brokenWord.length >= 15) brokenWords.push("­");
            }
            return brokenWords.join("");
        }
    
        var match;
        var word = "";
        var words = [];
        var patt = /\W/igm;
        var prevPos = 0;
        while (match = patt.exec(str))
        {
            var pos = match.index;
            var len = pos - prevPos;
            word = str.substr(prevPos, len);
    
            if (word.length > 15) word = BreakLargeWord(word);
    
            words.push(word);
            words.push(match[0]);
            prevPos = pos + 1;
        }
        word = str.substr(prevPos);
        if (word.length > 15) word = BreakLargeWord(word);
        words.push(word);
        var text = words.join("");
        return text;
    }
    
    //how to use
    var bigText = "Why is this text this big? Lets do a wrap here! aaaaaaaaaaaaa-bbbbb-eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
    var goodText = BreakLargeWords(bigText);
    

提交回复
热议问题