仅当包含字符串长度大于X时才替换

Replace only if the containing string length is greater than X

本文关键字:替换 大于 包含 字符串      更新时间:2023-09-26

我有一个正则表达式,它只匹配字符串中的一个字符。我想测试它的长度包含字符串,如果它大于4,然后进行替换。例如,正则表达式为/'d/。我想用replace的函数形式来匹配12345,而不是1234

类似:

text.replace(regex, function(match) {
       if (STRING.length > 4)
            return replacement
       else
            return match;
  });

注意:/'d/只是一个例子。我没有提到真正的正则表达式是为了关注我真正的问题,如上所示。

如果你想这样做:

function replaceWithMinLength (str, minLength) {
   str.replace(/'w+/, function(match) {
      if (match.length > minLength) {
        return match;
      } else {
        return str;
      }
   });
}

你这是本末倒置。你会过得更好:

if(string.length > 4) {
  string.replace('needle','replacement');
}

你说的"包含字符串"是指相同的数字序列吗?同时匹配它们:

text.replace(/'d{5,}/g, function(string) {
    return string.replace(/'d/g, function(match) {
        return replacement;
    });
});
例如

'd{5,}可以很容易地适应任何类型的字符串