Reputation: 391
I know this question is similar to THIS so apologies if considered a duplicate.
The result I'm trying to achieve is to check divs with a class of gallery-info
$('.gallery-info').each(function() {
});
I set up a condition to return a substring if the character count of each div is greater than 140 characters. (Twitter)
$('.gallery-info').each(function() {
var descLength = 140;
var str = $(this).text();
var patt = new RegExp(/[,;.:!()&\s$]/g);
if (str.length > descLength) {
$(this).text(str.substr(0, descLength) + "...");
}
});
IF
The last character of the substring matches the patt var. Return substring -1 and concat "..."
ELSE
Return substring and concat "..."
I've been having a brain fart on this and I believe I can achieve this in Vanilla JS with str.replace() and str.charAt() but I need to do this in jQuery.
Upvotes: 0
Views: 440
Reputation: 667
I think this works as you've described.
$('.gallery-info').each(function() {
var descLength = 140;
var str = $(this).text();
var patt = new RegExp(/[,;.:!()&\s$]/g);
if (str.length > descLength) {
var substring = str.substr(0, descLength);
var lastChar = substring[substring.length-1];
if (lastChar.match(patt)) {
$(this).text(str.substr(0, descLength -1) + "...");
} else {
$(this).text(str.substr(0, descLength) + "...");
}
}
});
Codepen
https://codepen.io/foozie3moons/pen/GMOBvw
Upvotes: 1
Reputation: 572
I think updating your IF condition with below should work fine.
if (str.length > descLength) {
if(patt.test(str[descLength-1])) {
$(this).text(str.substr(0, descLength-1) + "...");
} else {
$(this).text(str.substr(0, descLength) + "...");
}
}
CODEPEN: https://codepen.io/azimjs/pen/mBqjNY
Upvotes: 1