Javascript string ellipsising

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

[sourcecode language=’javascript’]
// 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”[/sourcecode]

The code

[sourcecode language=’javascript’]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; } } });[/sourcecode]If you're not using MooTools, you can use this variant instead:[sourcecode language='javascript']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; } }[/sourcecode]

Comments

One response to “Javascript string ellipsising”

  1. Mayur Avatar
    Mayur

    While working on my upcoming cool project, I wanted a JavaScript function that will perform an Ellipsis, bare in mind that I usually use C# and already have a .NET method that will do just that. However, in this case since my web application is 90% JS, I figured I could just do that client side. Here is what I came up with, I just wrote this 5 minutes ago, so use at your own risk.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.