Search code examples
htmltextmovewordsword-wrap

Move one letter words to next line


I have a responsive webpage. Is it possible to automatically move one letter words at the end of the line to next line.

Example:

A picture is worth
a thousand words.

instead of:

A picture is worth a
thousand words.


Solution

  • Silly but works. Just change the values in words and elements array to your needs

    function removeSingleCharLineBreak(){
    var words = ['a', 'i', 's', 'z', 'v', 'k', 'o', 'u', 
        'A', 'I', 'S', 'Z', 'V', 'K', 'O', 'U', '€',
        'na', 'za', 'do', 'Na', 'Za', 'Do',
        ];
    
    var elements = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'td', 'td'];
    
    $.each(words, function(index, word){
    
        var regex = new RegExp(" " + word + " ", "g");
    
        $.each(elements, function(index, element){
    
            $(element + ':contains( ' + word + ' )').each(function(){
    
                if (word == '€') 
                {
                    $(this).html(
                        $(this).html().replace(regex, ' ' + word + ' ')
                    );       
                }
                else
                {
                    $(this).html(
                        $(this).html().replace(regex, ' ' + word + ' ')
                    );                    
                }
    
            });
    
        });
    
    });
    

    }