JSFiddle - React, Tailwind, and code Playground

by wookiehangover

HTML

<div id="results"/>
<script type="text/javascript" 
src="https://getfirebug.com/firebug-lite.js">
{
    startOpened: true,
}
</script>

JavaScript

function fitBest(str, n){
    var r = /\W+\w*(?=$)/m,
        s = str.slice(0, n - 1)+"\n",
        t = /<\/?[^>]+>/g,
        c = /\/+/g,
        p = /<\/?[^>]+(?=$)/m,
        e = "...",
        new_str = s.slice(0, s.search(r)),
        tags = new_str.match(t),
        open_tags = [],
        i, l, q;
    
    if( new_str.match(p) ) {
        new_str = new_str.replace(p,"");
    }

    i = tags.length;
    while(i--){
        if( c.test(tags[i]) === false ){
            l = tags[i].match(/\w+/);
            q = "</"+l+">";
            
            if( ! new_str.match( q ) ){
                e = ( l == "a" ) ? q+e: e+q;
            }
        }
    }

    return (str.length <= n) ? str: new_str+e;
}

var text = "<p>loremipsum set dolor, est and <a href='http'>a bunch</a> of, other crap</p>",
    i = text.length;

//console.debug(fitBest(text, 67));

while(i--){
    console.debug(fitBest(text, i));
    //$('#results').append(fitBest(text, i)+"</br>" );
}