Using javascript substring () to create a read link

I am developing a classic ASP page that extracts some content from a database and creates a “Read more” link after the first 100 characters as follows:

<div class="contentdetail"><%=StripHTML(rspropertyresults.Fields.Item("ContentDetails").Value)%></div>

<script type="text/javascript">
    $(function() {

        var cutoff = 200;
        var text = $('div.contentdetail').text();
        var rest = $('div.contentdetail').text().substring(cutoff);
        if (text.length > 200) {
          var period = rest.indexOf('.');
          var space = rest.indexOf(' ');
          cutoff += Math.max(Math.min(period, space), 0);
        }

        var visibleText = $('div.contentdetail').text().substring(0, cutoff);

        $('div.contentdetail')
            .html(visibleText + ('<span>' + rest + '</span>'))
            .append('<a title="Read More" style="font-weight:bold;display: block; cursor: pointer;">Read More&hellip;</a>')
            .click(function() {
                $(this).find('span').toggle();
                $(this).find('a:last').hide();
            });

        $('div.contentdetail span').hide();
    });
</script>

However, the script obviously just turns off the text after 100 characters. It is advisable that I continue to write the text until the first period or space, for example. Can this be done?

Thanks.

+5
source share
3 answers
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 a bit. EDIT : fixed EDIT bug : improved QoL

+3
source

What 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...
}

{0,20} 20 , 100 . . {20,} , .

, :

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

HTML - . visibleText textToHide - < &, , XSS .

text() div span , , .

+2

Here's a pretty simple approach to getting word level endings and shooting at your character limit.

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
source

All Articles