Ellipsis Function with Limiting Options
ellipsis,strings,javascript, truncate
by mmansion
JavaScript
var lines = [
'at once published an edict forbidding all persons',
'where an old serving woman sat alone',
'this good woman had never heard speak of king\'s proclamations',
'no sooner than she seized the spindle than she pricker her finger'
];
/**
* @method - ellipsis
*
* @returns {String} - truncated string with ellipsis appended to end
*
* @desc - shortensa length of a string argument based on params
*
* @param line {String} - string of text to truncate and add ellipsis to
*
* @param length {Number} - integer length limit of truncation
*
* @param breakSpaceLimit {Number} - used to determine an accepted distance from last index position
* after a truncation that the function should look for a "space"
* character to break the text on. if the limit is exceded the
* text will break mid-word
* @requires - jQuery
*/
var ellipsis = function(line, length, breakSpaceLimit) {
var ellipsisChar = '…';
//breakSpaceLimit is used to determine the distance from the last index
//that a "space" break may occur on. If the limit is exceded then the
//break can happen within a word
//console.log(string.substring(0,length));
if(line.length > length) {
//reduce string length using substring method
line = line.substring(0,length);
//determine if line breaks on a letter
if(line.charCodeAt(line.length-1) !== 32) {
if(breakSpaceLimit) {//check against limit
//search truncated line for remaining spaces to see if there is a reasonable breakpoint
spaces = jQuery.grep(line, function(char) {
//console.log(char);
return (char.charCodeAt(0) === 32); //return any remaining spaces in line
});
if(spaces.length) {
...