Mark Mark - 2 months ago 10
jQuery Question

Read More | Duplicating characters

I am using this code to add read more / less paragraph. Its working fine but duplicating the word eg. management breaks into manag & gement resulting spelling mistake.Check screenshot.

var showChar = 370;
var ellipsestext = "...";
var moretext = "more";
var lesstext = "less";
$('.more').each(function() {
var content = $("p", this).html();

if(content.length > showChar) {

var c = content.substr(0, showChar);
var h = content.substr(showChar-1, content.length - showChar);

var html = c + '<span class="moreelipses">'+ellipsestext+'</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">'+moretext+'</a></span>';

$("p", this).html(html);
}

});

$(".morelink").click(function(){
if($(this).hasClass("less")) {
$(this).removeClass("less");
$(this).html(moretext);
} else {
$(this).addClass("less");
$(this).html(lesstext);
}
$(this).parent().prev().toggle();
$(this).prev().toggle();
return false;
});

Answer

You have an off-by-one bug (also called off-by-one error).

Replace

content.substr(showChar-1, content.length - showChar);

with

content.substr(showChar, content.length - showChar);