How to limit html content excluding tags, styles in JavaScript?
e.g. Consider the below scenario;
html: Welcome! Vips Patel to the site Logout.
limit: 12
desired output: Welcome! Vips.
For above desired output, below logic is implemented.
function limitHTML (html, limit)
{
limit = parseInt(limit, 10);
var counter = 0;
//Step 1:
//splits the html content with "<"
//So the resultant array has
// 1) "" 2) i>Welcome!
// 3)"" 4) b>Vips Patel,.....
// 5)"" 6) /b> to the site
// 7)"" 8) /i>
// 9)"" 10) a>Logout
//11)"" 12) /a>.
var a1 = html.split("<");
var i = 0;
//Step 2:
//Again split every element with ">" and check it has length of 2
//If yes, then second element has all text of html tag.
//Process text of html tag available in second element of array.
// i>Welcome! => 1)i and 2) Welcome!
while (counter <= limit && i < a1.length) {
var txt = a1[i];
var a2 = txt.split(">");
if (a2.length > 1) {
counter += a2[1].length;
}
i++;
}
//increment i if any for last closing tag
i++;
//Step 3:
//If count reaches then splice the array and return string
//after joining with "<"
a1.splice(i, a1.length - i);
var str = a1.join("<");
return str;
}
Wednesday, February 24, 2010
Subscribe to:
Posts (Atom)