Javascript string ellipsising

2009-08-05 – 4:03pm

Putting ellipses into strings that are too long has been around for a very long time. Unfortunately, Javascript doesn’t offer a native method of doing this, so below is a little function that’ll do it for you.

This function returns a copy of the string it’s called on, ellipsised, and takes three parameters:

toLength (required) The number of characters to truncate the string to (or 0 to disable ellipsising)

where (optional, default ‘end’) A string representing where the ellipsis should be placed — ‘front’, ‘middle’, or ‘end’

ellipsis (option, default ‘\u2026′) A string to be used as the ellipsis.

Examples

// Our clichéd string
var s = 'Jackdaws love my great big sphinx of quartz';

alert(s.ellipsise(10));
// Alerts "Jackdaws l…"

alert(s.ellipsise(10, 'front'));
// Alerts "… of quartz"

alert(s.ellipsise(10, 'middle', 'pony'));
// Alerts "Jackdponyuartz"

The code

String.implement({
	ellipsise: function(toLength, where, ellipsis) { // Where is one of ['front','middle','end'] -- default is 'end'
		if (toLength < 1) return this;
		ellipsis = ellipsis || '\u2026';
		if (this.length < toLength) return this;
		switch (where) {
			case 'front':
				return ellipsis + this.substr(this.length - toLength);
				break;
			case 'middle':
				return this.substr(0, toLength / 2) + ellipsis + this.substr(this.length - toLength / 2)
				break;
			case 'end':
			default:
				return this.substr(0, toLength) + ellipsis;
				break;
		}
	}
});

If you’re not using MooTools, you can use this variant instead:

String.prototype.ellipsise = function(toLength, where, ellipsis) { // Where is one of ['front','middle','end'] -- default is 'end'
	if (toLength < 1) return this;
	ellipsis = ellipsis || '\u2026';
	if (this.length < toLength) return this;
	switch (where) {
		case 'front':
			return ellipsis + this.substr(this.length - toLength);
			break;
		case 'middle':
			return this.substr(0, toLength / 2) + ellipsis + this.substr(this.length - toLength / 2)
			break;
		case 'end':
		default:
			return this.substr(0, toLength) + ellipsis;
			break;
	}
}

Add your voice

Spam protection by WP Captcha-Free