JSFiddle - React, Tailwind, and code Playground

HTML

<div id="foo">
  <span>hello there I am a string really really long, I wonder how many lines I have</span> 
</div>

CSS

#foo {
    width:100px;
    background:red;
}

JavaScript

var $span = $('#foo span');


avoidBastardWord( $span );

function avoidBastardWord( text_element )
{
    var string = text_element.text();
    var parent = text_element.parent();
    var parent_width =  parent.width();
    var parent_height = parent.height();
    
    // determine how many lines the text is split into
    var lines = parent_height / getLineHeight(text_element.parent()[0]);

    // if the text element width is less than the parent width,
    // there may be a widow
    if ( text_element.width() < parent_width )
    {
        // find the last word of the entire text
        var last_word =  text_element.text().split(' ').pop();
        
        // remove it from our text, creating a temporary string
        var temp_string = string.substring( 0, string.length - last_word.length - 1);
        
        // set the new one-word-less text string into our element
        text_element.text( temp_string );
        
        // check lines again with this new text with one word less
        var new_lines = parent.height() / getLineHeight(text_element.parent()[0]); 

        // if now there are less lines, it means that word was a widow
        if ( new_lines != lines )
        {
            // separate each word
            temp_string = string.split(' ');
            
            // put a space before the second word from the last
            // (the one before the widow word)
            temp_string[ temp_string.length - 2 ] = '<br>' + temp_string[ temp_string.length - 2 ] ;
            
            // recreate the string again
            temp_string = temp_string.join(' ');
            
            // our element html becomes the string
            text_element.html( temp_string );
        }
        else
        {
            // put back the original text into the element
            text_element.text( string );
        }
        
    }
    
}

// taken from 
//...