James Yang
James Yang

Reputation: 1416

how to truncate html string in js

I have a page displaying text in html entity into a div node, like below one:

<p>isdjf</p>osdf&kdjf;'ldsf."jdof&ids want to truncate it to 10 letters length in js, but want to avoid break html entities, how to achieve that correctly? substr?

html entity break is as below:

var str = '0123456>abc';
console.log( str.substr(0,10) );  // -> "0123456&#x"

Do you see the problem?

Upvotes: 0

Views: 266

Answers (1)

Jeroen
Jeroen

Reputation: 41

function truncate(enitityEncodedString){

    var string, count, pos;

    string = '';

    count = 0;

    while(count <= 10){

        if(enitityEncodedString.search(/&#.{2,3};/) === 0){

            pos = enitityEncodedString.indexOf(';') + 1;

            string += enitityEncodedString.substr(0, pos);

            enitityEncodedString = enitityEncodedString.substr(pos);

        }else{

            string += enitityEncodedString[0];

            enitityEncodedString = enitityEncodedString.substr(1);

        }

        count++;

    }

    return string;


}

Check for html entities at the beginning of the encoded string. If so, concat that html entity to the return string (I used .indexOf() to get the length of the html entity, assuming the first semicolon means the end of that same html entity). Otherwise, just add the first character to the return string. Repeat untill you got 10 characters.

Maybe not the prettiest way, but it works.

Upvotes: 2

Related Questions