Search code examples
javascriptsubstr

javascript substr chars without counting spaces


I have a text description with css of

white-space: pre-wrap;

and it includes spaces and new lines etc...

I would like to limit number of characters in description without counting spaces:

description = description.substr(0,100);

Of course I need to preserve description formatting.

How could I do that?


Solution

  • Try this function. This returns exactly desired value:

    function mySubstr(a/*description*/, c/*count*/){
        var l=0, dif=0, p=c, 
              dt=[a.substr(0, c)];
        while((l=dt.join("").replace(/\s/g, "").length)<c){
             dt.push(a.substr(p, dif=c-l));
             p+=dif;
        }
        return dt.join("");
    }
    console.log(mySubstr("1    2 $- 8 58 9&8 85 0j g fg hc 6 4 34 8", 16));
    

    check result online!


    Added part (method2 - updated version):

    You can try this. This version supports multi \s too:

    function Substr2(desc, c/*count*/){
        var r="", s=0, m=0, res, ok;
        desc.replace(/(.+?)(\s+)/g, function(a,b,d){
            if(ok) return;  
            m+=b.length;
            r+=a;
            res=r.substr(0, m+s-(m-c));
            if(m>=c) ok=1;
            s+=d.length;
        });
        return res;
    };
    
    console.log(Substr2("1 2 $- 8 58 9&8 85 0j g fg hc 6 4 34 8", 16));