rod
rod

Reputation: 309

jquery add line break and truncate + add "..." after x amount of characters

I'm trying to figure out a way to accomplish 2 things:

1. A line break after 4 characters or first word.
2. Truncate + add "..." (only if the amount of characters exceed 20 characters)

Example: 2008 WALKER STATION THE BRIDGE 1.5L

Would like it to display:
2008
WALKER STATION ...

I need #1 to happen every time, but only #2 if the text is more 20 characters.

I've got the line breaking down with the following code:

$(window).load(function(){
    $(".wine-name").each(function() {
    var html = $(this).html().split(" ");
    html = html[0] + "<br>" + html.slice(1).join(" ");
    $(this).html(html);
});

HTML:

<div class="wine-name">2008 WALKER STATION THE BRIDGE 1.5L</div>

Upvotes: 1

Views: 3164

Answers (4)

Šime Vidas
Šime Vidas

Reputation: 185923

Here you go:

$( '.wine-name' ).each( function () {
    var words, str;

    words = $( this ).text().split( ' ' );
    str = words.shift() + '<br>';

    while ( words.length > 0  && ( str.length + words[0].length ) < 24 ) {
        str += ' ' + words.shift();
    } 

    if ( words.length > 0 ) {
        str += ' ...';
    }

    $( this ).html( str );    
});

Live demo: http://jsfiddle.net/XpmpQ/1/

Upvotes: 1

Rusty Fausak
Rusty Fausak

Reputation: 7525

I think you are looking for something like this:

var s = "2008 hello world";
// Find the index of the first space or use 4
var i = Math.min(4, s.indexOf(" "));
var part1 = s.substr(0, i);
var part2 = s.substr(i);
// Add ellipsis if part2 is longer than 5 characters
if (part2.length > 5) part2 = part2.substr(0, 5) + '..';
// Output for testing
alert('"' + part1  + '", "' + part2 + '"');

jsFiddle demo

Upvotes: 0

David Thomas
David Thomas

Reputation: 253318

One way of doing this is to use:

var string, p1,p2,p3;

$('.wine-name').each(
    function(){
        string = $(this).text();
        p1 = string.substring(0,4);
        p2 = string.substring(5);
        if (p2.length > 20){
            p3 = p2.substring(0,19) + '...';
            p2 = p3;
        }
        newString = p1 + '<br />' + p2;
        $(this).html(newString);
    });

JS Fiddle demo.

Upvotes: 1

Can Poyrazoğlu
Can Poyrazoğlu

Reputation: 34780

Well, you may set up it the CSS way using text-overflow property which is pretty weill supported (but not in FF for some strange reason), depending on your needs, the CSS way (without any script) would do the job, or even better. Have a look at Google by searching text-overflow ellipsis if you don't know what I'm talking about.

Sorry to bother if you already know this, I just pointed out an alternative that I thought would help.

Upvotes: 0

Related Questions