简体   繁体   中英

Replace last matched character in substring using jquery / regex

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM