简体   繁体   English

使用jQuery / Regex替换子字符串中的最后一个匹配字符

[英]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检查div

$('.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. 我设置了一个条件,如果每个div的字符数大于140个字符,则返回一个子字符串。 (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. 子字符串的最后一个字符与patt var匹配。 Return substring -1 and concat "..." 返回子字符串-1和concat“ ...”

ELSE 其他

Return substring and concat "..." 返回子字符串和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. 我对此一直很放屁,我相信我可以在Vanilla JS中使用str.replace()和str.charAt()来实现这一点,但是我需要在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 https://codepen.io/foozie3moons/pen/GMOBvw

I think updating your IF condition with below should work fine. 我认为使用以下更新您的IF条件应该可以正常工作。

  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 CODEPENhttps//codepen.io/azimjs/pen/mBqjNY

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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