我有一个只匹配字符串中一个字符的正则表达式。我想测试它的 containing string 的长度,如果它大于 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;
}
});
}
关于javascript - 仅当包含的字符串长度大于 X 时才替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16263483/