Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular Widow Fix Filter
(function() {
'use strict';
angular.module('webApp.filters')
.filter('widowFix', function() {
return function(input) {
if (input !== undefined) {
var wrapper= document.createElement('div');
wrapper.innerHTML = input;
var elems = wrapper.querySelectorAll('div, p, h1, h2, h3, h4');
var minWords = 5;
angular.forEach(elems, function(value, key){
var htmlString = elems[key].innerHTML;
htmlString = htmlString.replace(/>\s+</g,'');
var wordArray = htmlString.trim().split(' ');
if (wordArray.length > minWords) {
wordArray[wordArray.length-2] += '\u00A0' + wordArray[wordArray.length-1];
wordArray.pop();
htmlString = wordArray.join(' ');
}
elems[key].innerHTML = htmlString;
});
return wrapper.innerHTML;
}
};
})
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment