0

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this. I knew I was on the right track. Life saver.
1

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

1 Comment

Thanks for the answer. However, I believe it to be unnecessary to split the string since strings are inherently character arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.