Javascript - Truncate Innerhtml String After N Numbers Of Characters With Strip Any Tag Or Arrtibute Inside It
I wastry to add three dots after 130 characters of string which grabbed from a DIV through the JavaScript innerHTML method. Inside the innerHTML may have more tags and attributes w
Solution 1:
you can try this. Note that this code updates the html directly, if you wish to keep the original content, clone the node you want to play with, and use the cloned version to run the trim:
functionmap_node(f_objNode,f_currLimit){
for(var i=0;i<f_objNode.childNodes.length;i++){
var l_node = f_objNode.childNodes[i];
if(f_currLimit == 0){ //max length exceeded, remove node
l_node.remove();
i--; //move index backwards to account for the deleted nodecontinue;
}elseif(l_node.nodeType == 3){ //textnodevar l_strText = l_node.nodeValue;
if((f_currLimit - l_strText.length) < 0){ //the text length//exceeds the limit//trim and 0 the limit
l_node.nodeValue = l_strText.substring(0,f_currLimit) + '...';
f_currLimit = 0;
}else{ //max length is below the text length, update the limit
f_currLimit -= l_strText.length
}
}
//process the children of the node,//you can add check here to skip the call if no children
f_currLimit = map_node(l_node,f_currLimit);
}
return f_currLimit
}
//this is how you use it.functiontest(){
var l_textLimit = 100; //your limitvar l_div = document.getElementById("test-div"); //your nodevar l_data = map_node(l_div,l_textLimit); //parse the shit out of it//not really used, but if you replace the //the limit integer with {} you can add postprocessingconsole.log(l_data)
}
as a side note, be aware of parsing as a way to tokenize html. It certainly has its uses, but it can get pretty complicated if you want to maintain the structure of the node. In such cases, it is easier and more efficient to roll with the DOM directly. Going that direction also has issues- larger DOM (sub)trees are not ideal target for recursive processing, so you need to pick your approach for the concrete context.
Post a Comment for "Javascript - Truncate Innerhtml String After N Numbers Of Characters With Strip Any Tag Or Arrtibute Inside It"