问题是我想在1st
发生时替换某个字符串,直到发生为止nth
。哪里n
可以是任何数字。
示例测试字符串:
// 'one-two' the string I want to search
var str = "73ghone-twom2j2hone-two2717daone-two213";
我需要用替换第一个"one-two"
直到第n个匹配项"one"
。
//so in terms of function. i need something like:
function replaceByOccurence(testSring, regex, nthOccurence) {
//implementation here
}
给定上面的功能,如果我通过3
as nthOccurence
,它应该将第一个匹配项替换为第三个匹配项。如果我通过2
as nthOccurence
,它应该将第一个匹配替换为第二个匹配,因此在我们的示例中,如果我们通过2
,则应该返回"73ghonem2j2hone2717daone-two213"
。请注意,第三个"one-two"
不会替换为"one"
。
有人可以帮忙吗?我搜索了,但是在这里找不到类似的问题。
迷你更新[已解决:请检查最近的更新]
因此,我使用了@anubhava的第一个解决方案,并尝试将其作为函数放入String中。我这样写:
String.prototype.replaceByOccurence = function(regex, replacement, nthOccurence) {
for (var i = 0; i < nthOccurence; i++)
this = this.replace(regex, replacement);
return this;
};
//usage
"testtesttest".replaceByOccurence(/t/, '1', 2);
显然我遇到了参考错误。它说left side assignment is not a reference
且指向this = this.replace(regex, replacement)
。
最后更新
我将代码更改为此:
String.prototype.replaceByOccurence = function (regex, replacement, nthOccurence) {
if (nthOccurence > 0)
return this.replace(regex, replacement)
.replaceByOccurence(regex, replacement, --nthOccurence);
return this;
};
现在正在工作。
我认为简单的循环可以完成这项工作:
function replaceByOccurence(input, regex, replacement, nthOccurence) {
for (i=0; i<nthOccurence; i++)
input = input.replace(regex, replacement);
return input;
}
并将其称为:
var replaced = replaceByOccurence(str, /one-two/, 'one', 3);
编辑:没有循环的另一个版本
function replaceByOccurence(input, regex, replacement, num) {
i=0;
return input.replace(regex, function($0) { return (i++<num)? replacement:$0; });
}
并将其称为:
var replaced = replaceByOccurence(str, /one-two/g, 'one', 3);
//=> 73ghtwom2j2htwo2717datwo213
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句