benjamincharity
6/30/2015 - 3:13 PM

Wrap lines in spans that don't go past a certain character count while respecting words.

Wrap lines in spans that don't go past a certain character count while respecting words.

angular.module('common')
.filter('split', function() {

    //
    // Helper function
    // Return as many words as possible without going past the limit
    var trimWords = function(string, limit) {
        var cutAtCharacterLimit = string.slice(0, limit).trim();
        var indexOfLastSpace = cutAtCharacterLimit.lastIndexOf(' ');
        var cutAtLastSpace;

        // If there is more than one word
        if( indexOfLastSpace > 0 ) {
            cutAtLastSpace = cutAtCharacterLimit.slice(0, indexOfLastSpace);
        } else {
            // Otherwise return the string
            cutAtLastSpace = string;
        }

        return cutAtLastSpace;
    };


    return function(input, limit) {

        if (!input) {
            return 'No string to split.';
        }

        var wrappedLines = '';
        var wrapper = {
            start: '<span class=\'line\'>',
            end: '</span>'
        };


        //
        // Split a sentence into multiple lines wrapped by <span>s
        // Not sure how to do this without the numbers
        while( input.length > 0 ) {
            var tempString = trimWords(input, limit);

            wrappedLines += wrapper.start + tempString + wrapper.end;
            input = input.slice(tempString.length, input.length).trim();
        }


        return wrappedLines;

    };

});