Return to Snippet

Revision: 14986
at June 19, 2009 05:09 by segdeha


Updated Code
/**
 * Author: Andrew Hedges, [email protected]
 * License: free to use, alter, and redistribute without attribution
 */

/**
 * Truncate a string to the given length, breaking at word boundaries and adding an elipsis
 * @param string str String to be truncated
 * @param integer limit Max length of the string
 * @return string
 */
var truncate = function (str, limit) {
	var bits, i;
	if (STR !== typeof str) {
		return '';
	}
	bits = str.split('');
	if (bits.length > limit) {
		for (i = bits.length - 1; i > -1; --i) {
			if (i > limit) {
				bits.length = i;
			}
			else if (' ' === bits[i]) {
				bits.length = i;
				break;
			}
		}
		bits.push('...');
	}
	return bits.join('');
};
// END: truncate

Revision: 14985
at June 19, 2009 05:07 by segdeha


Updated Code
/**
 * Author: Andrew Hedges, [email protected]
 * License: free to use, alter, and redistribute without attribution
 */

/**
 * Truncate a string to the given length, breaking at word boundaries and adding an elipsis
 * @param string str String to be truncated
 * @param integer limit Max length of the string
 * @return string
 */
var truncate = function (str, limit) {
	var bits, i;
	if (STR !== typeof str) {
		return '';
	}
	bits = str.split('');
	if (bits.length > limit) {
		for (i = bits.length - 1; i > -1; --i) {
			if (i > limit) {
				bits.length = i;
			}
			else if (' ' === bits[i]) {
				bits.length = i;
				break;
			}
		}
		bits.push('�');
	}
	return bits.join('');
};
// END: truncate

Revision: 14984
at June 19, 2009 05:06 by segdeha


Initial Code
/**
 * Truncate a string to the given length, breaking at word boundaries and adding an elipsis
 * @param string str String to be truncated
 * @param integer limit Max length of the string
 * @return string
 */
var truncate = function (str, limit) {
	var bits, i;
	if (STR !== typeof str) {
		return '';
	}
	bits = str.split('');
	if (bits.length > limit) {
		for (i = bits.length - 1; i > -1; --i) {
			if (i > limit) {
				bits.length = i;
			}
			else if (' ' === bits[i]) {
				bits.length = i;
				break;
			}
		}
		bits.push('…');
	}
	return bits.join('');
};
// END: truncate

Initial URL

                                

Initial Description

                                

Initial Title
Truncate a string to a set length, breaking at word boundaries

Initial Tags
javascript

Initial Language
JavaScript