0

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?

3
  • What do you mean by avoid break html entities ? Commented Nov 7, 2015 at 2:00
  • what is html entities break? Commented Nov 7, 2015 at 2:06
  • @sumeetkumar, please see update Commented Nov 7, 2015 at 2:51

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.