开发者

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

开发者 https://www.devze.com 2023-04-07 03:29 出处:网络
I\'m trying to figure out a way to accomplish 2 things: 1. A line break after 4 characters or first word.

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 c开发者_如何学编程haracters 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>


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/


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号