Last active
December 16, 2015 17:44
-
-
Save robcmills/7f6afb683bfd4f383e60 to your computer and use it in GitHub Desktop.
Simple function to trim html content to a specified length.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// var htmlIn = '<div>Hello world!</div>'; | |
// var htmlIn = '<div>Hello <b><i>world!</i></b></div>'; | |
// var htmlIn = '<div><ol><li>Hello</li><li><b>world!</b></li></ol></div>'; | |
// var htmlIn = '<div>1</div><div>2</div><div><br/></div><ol><li><b><i>Hello<i><b></li><li><b>world!</b></li></ol></div>'; | |
var htmlIn = '<div>Hello </div><div><br/></div><div>world!</div>'; | |
var trimTo = 8; // trim to this length | |
var trimHtml = function(html, trim) { | |
var length = 0; | |
var i = 0; | |
var trimmed = ''; | |
var openTags = []; | |
var getTag = function() { | |
var tag = ''; | |
while(html[i] !== '>') { | |
tag += html[i]; | |
i++; | |
} | |
i++; | |
return tag + '>'; | |
}; | |
var closeTags = function() { | |
while(openTags.length) { | |
trimmed += openTags.pop().replace('<', '</'); | |
} | |
}; | |
var e = function() { | |
if(length < trim) { | |
if(html[i] === '<' && html[i+1] !== '/') { | |
// open tag | |
var tag = getTag(); | |
if(tag.indexOf('/') < 0) { | |
openTags.push(tag); | |
} | |
trimmed += tag; | |
return; | |
} | |
if(html[i] === '<' && html[i+1] === '/') { | |
// close tag | |
var tag = getTag(); | |
openTags.pop(); | |
trimmed += tag; | |
return; | |
} | |
trimmed += html[i]; | |
length++; | |
} else { | |
closeTags(); | |
i += html.length; | |
return; | |
} | |
i++; | |
}; | |
while(i <= html.length) { | |
e(); | |
} | |
return trimmed; | |
}; | |
console.log('htmlIn', htmlIn); | |
console.log('htmlOut', trimHtml(htmlIn, trimTo)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment