Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace only if the containing string length is greater than X

I've a regex that will only match one character of the strings. I want to test the lentgh of its containing string and if it was greater than 4 then make the replacement. For example, the regex is /\d/. I want to use the functional form of replace to match 12345 but not 1234.

Something like:

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

Note: /\d/ is just an example. I didn't mention the real regex to focus on my real question, illustrated above.

like image 674
Iryn Avatar asked Jan 14 '23 12:01

Iryn


2 Answers

Or if you want to do it that way:

function replaceWithMinLength (str, minLength) {
   str.replace(/\w+/, function(match) {
      if (match.length > minLength) {
        return match;
      } else {
        return str;
      }
   });
}
like image 71
Chris Avatar answered Jan 31 '23 09:01

Chris


You're putting the horse before the cart. You would be better off:

if(string.length > 4) {
  string.replace('needle','replacement');
}
like image 31
oomlaut Avatar answered Jan 31 '23 09:01

oomlaut