javascript 仅当包含的字符串长度大于 X 时才替换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16263483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace only if the containing string length is greater than X
提问by Iryn
I've a regex that will only match one character of the strings. I want to test the lentgh of its containing stringand 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
.
我有一个只匹配字符串中的一个字符的正则表达式。我想测试其包含字符串的长度,如果它大于 4,则进行替换。例如,正则表达式是/\d/
. 我想使用 replace 的功能形式来匹配12345
但不是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.
注意:/\d/
只是一个例子。我没有提到真正的正则表达式来关注我真正的问题,如上所示。
回答by Christiaan
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;
}
});
}
回答by oomlaut
You're putting the horse before the cart. You would be better off:
你把马放在手推车之前。你会更好:
if(string.length > 4) {
string.replace('needle','replacement');
}
回答by Ry-
So by “containing string”, you mean like the same sequence of digits? Match them all at once:
那么“包含字符串”是指相同的数字序列吗?同时匹配它们:
text.replace(/\d{5,}/g, function(string) {
return string.replace(/\d/g, function(match) {
return replacement;
});
});
For example. The \d{5,}
can easily be adapted to any type of string-thing.
例如。将\d{5,}
可以很容易地适用于任何类型的字符串的东西。