Skip to content

Instantly share code, notes, and snippets.

@jamesmusgrave
Created November 12, 2014 12:24
Show Gist options
  • Save jamesmusgrave/708ad110bf9e3b258bf9 to your computer and use it in GitHub Desktop.
Save jamesmusgrave/708ad110bf9e3b258bf9 to your computer and use it in GitHub Desktop.
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