Created
November 12, 2014 12:24
-
-
Save jamesmusgrave/708ad110bf9e3b258bf9 to your computer and use it in GitHub Desktop.
Angular Widow Fix Filter
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
(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