Using javascript substring() to create a read more link

后端 未结 3 1726
予麋鹿
予麋鹿 2020-12-11 18:33

I\'m developing a Classic ASP page that pulls some content from a database and creates a Read more link after the first 100 characters as follows;

相关标签:
3条回答
  • 2020-12-11 19:22

    Here is a fairly simple approach to getting endings at the word level, and shooting for about your given limit in characters.

    var limit        = 100,
        text         = $('div.contentdetail').text().split(/\s+/),
        word,
        letter_count = 0,
        trunc        = '',
        i            = 0;
    
    while (i < text.length && letter_count < limit) {
      word         = text[i++];
      trunc       += word+' ';
      letter_count = trunc.length-1;
    
    }
    
    trunc = $.trim(trunc)+'...';
    console.log(trunc);
    
    0 讨论(0)
  • 2020-12-11 19:30
    var cutoff = 100;
    var text = $('div.contentdetail').text();
    var rest = text.substring(cutoff);
    if (text.length > cutoff) {
      var period = rest.indexOf('.');
      var space = rest.indexOf(' ');
      cutoff += Math.max(Math.min(period, space), 0);
    }
    // Assign the rest again, because we recalculated the cutoff
    rest = text.substring(cutoff);
    var visibleText = $('div.contentdetail').text().substring(0, cutoff);
    

    EDIT: shortened it a bit. EDIT: Fixed a bug EDIT: QoL improvement

    0 讨论(0)
  • 2020-12-11 19:39

    How about:

    var text= $('div.contentdetail').text();
    var match= text.match( /^(.{100}([^ .]{0,20}[ .])?)(.{20,})$/ );
    if (match!==null) {
        var visibleText = match[1];
        var textToHide = match[3];
        ...do replacement...
    }
    

    The {0,20} will look forward for a space or period for up to 20 characters before giving up and breaking at exactly 100 characters. This stops an extremely long word from breaking out of the length limitation. The {20,} at the end stops a match being made when it would only hide a pointlessly small amount of content.

    As for the replacement code, don't do this:

    .html(visibleText + ('<span>' + textToHide + '</span>'))
    

    This is inserting plain-text into an HTML context without any escaping. If visibleText or textToHide contains any < or & characters you will be mangling them, perhaps causing a XSS security problem in the process.

    Instead create the set the text() of the div and the span separately, since that's the way you read the text in the first place.

    0 讨论(0)
提交回复
热议问题