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.
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;
}
});
}
You're putting the horse before the cart. You would be better off:
if(string.length > 4) {
string.replace('needle','replacement');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With