Search code examples
javascriptword-wrap

Javascript - Getting the last word in a line


Here is an example:

<div><span style="font-size:15px;">some text here which is </span>
<span style="color:red;">split automatically by the browser.</span></div>

which the browser renders as (with styles of course):

some text here which is split
automatically by the browser.

I am building up a javascript application which has to understand the last word in each line (split in this case). Currently I am using the CSS white-space property to deal with overflow text. Therefore, the browser will not give me a clue about where it does break the line. So, what would be a nice function to understand the last word in each line?

EDIT

I am using pure-javascript, so jQuery would not be an option and the white-space property is applied to the div. So actually, think the div as a line renderer.


Solution

  • You can rewrite the whole sentence word-by-word keeping track of the height changes. Here is some explanation via code:

    HTML:

    <div id="flop" class="foobar">Lorem ipsum dolor sit amet, consectetur adipisicing 
    elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim 
    ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea 
    commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit 
    esse cillum dolore eu fugiat nulla pariatur.</div>
    <br>
    <button value="Go" onclick="foo();">Go</button>​​​​​​​​​​​​​​​​​​​​​​​​​​​​
    

    Script:

    function foo(){
        var d = document.getElementById('flop');
        var t = d.innerHTML;
        var w = t.split(' ');       
    
        d.innerHTML = w[0];
        var height = d.clientHeight;
        for(var i = 1; i < w.length; i++){
            d.innerHTML = d.innerHTML + ' ' + w[i];
    
            if(d.clientHeight > height){
                height = d.clientHeight;
                console.log(w[i-1]);
            }
        }
    }
    

    This will log the last words of each line to the console except the last line. I leave that to you. The nice thing about this solution is that even after a window resize it works correctly.

    By the way, Yi Jiang deserves all the credit for his answer to this question here on SO.