替换字符串的第1到第n个匹配.javascript

replacing the 1st to nth match of the string. javascript

本文关键字:javascript 到第 字符串 替换      更新时间:2023-09-26

问题是我想替换1st出现到nth出现的某个字符串。其中n可以是任意数

示例测试字符串:

// 'one-two' the string I want to search
var str = "73ghone-twom2j2hone-two2717daone-two213";

我需要用"one"替换第一个"one-two"直到第n个匹配。

//so in terms of function. i need something like:
function replaceByOccurence(testSring, regex, nthOccurence) {
    //implementation here
}

给定上面的函数,如果我将3传递为nthOccurence,它应该替换第一个匹配直到第三个匹配。如果我传递2作为nthOccurence,它应该替换第一个匹配直到第二个匹配,所以在我们的例子中,如果我们传递2,它应该返回"73ghonem2j2hone2717daone-two213"。注意,第三个"one-two"没有被替换为"one"

有人能帮忙吗?我搜索了一下,但我在这里找不到类似的问题。


迷你更新 [SOLVED: check last Update]

所以我使用@anubhava的第一个解决方案,并试图把它放在字符串作为函数。我是这样写的:

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);

EDIT:另一个版本不循环

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

像这样:

var myregex = /(.*?one-two){3}(.*)/;
result = yourString.replace(myregex, function(match) {
  return  match(1).replace(/one-two/g, "one") + match(2);
});
  • 匹配的是整个字符串
  • match(1)是字符串的开始,直到第三个one-two
  • match(2)是字符串
  • 的剩余部分。
  • 我们将字符串替换为转换匹配(1)(其中我们将one-two替换为one)加上字符串的其余部分