Is there a way to truncate a string in the middle using CSS or JS?

css, javascript

Solution

With css, you can easily use ellipsis, but only at the end of the text.

However, there is a jQuery plugin called `dotdotdot`, which can do this.

Here's it's page: DotDotDot

One of their demo examples shows, how a long URL can be turned into `www.website.com/that/should/... /file.html`

I spent some time trying to get this working properly, and it's still not quite perfect, but works pretty well.

// @param element    obtained with $("selector")
// @param spacer     ' ' for text, or '/' for links.
// @param position   number of words to leave at end
function doEllipsis(element, spacer, position) {
    $(element).data('ell-orig', $(element).html());
    $(element).data('ell-spacer', spacer);
    $(element).data('ell-pos', position);

    var pieces = $(element).html().split(spacer);
    if (pieces.length > 1) {

        var building = "";

        var i = 0;


        // for "position" to mean "fraction where to wrap" (eg. 0.6), use this:
        // for (; i < pieces.length*position; i++) {    

        for (; i < pieces.length-position; i++) {
            building += pieces[i] + spacer;
        }


        building += '<span class="ell">';

        for (; i < pieces.length; i++) {
            building += pieces[i] + spacer;
        }

        building += '</span>';

        $(element).html(building);

        $(element).dotdotdot({
            after: 'span.ell',
            wrap: 'letter'
        });
    }
}

// use to redraw after the size changes etc.
function updateEllipsis(element) {
    var orig = $(element).data('ell-orig');
    var spacer = $(element).data('ell-spacer');
    var pos = $(element).data('ell-pos');

    $(element).trigger("destroy");
    $(element).empty();

    $(element).html(orig);

    doEllipsis(element, spacer, pos);
}

Here's a fiddle of this example (it uses a copy hosted on my dropbox, so it's quite sure that it won't work forever).

It is responsive (to some extent, anyway), and puts the ellipsis exactly where you tell it to.

Problem

I need a way to truncate a string in the middle for a mobile app. The string has important info at the end that I always want to be visible. I haven't been able to find a CSS method to do it in the middle of the string, just the beginning or end. I am working on a method to do this in JS, but I would think this has been addressed already and I don't want to re-invent the wheel. The thing I see becoming an issue is that I need it to be dynamic based on the screen size. I can't simply say if `string.length > 100` then truncate. I need to see what will fit, then truncate, and make it listen for changes to size like if the orientation is changed.

Original source

Related problems