我正在尝试将变量添加到函数调用中

原始功能来自这里
Find and replace nth occurrence of [bracketed] expression in string

var s = "HELLO, WORLD!";
var nth = 0;
s = s.replace(/L/g, function (match, i, original) {
nth++;
return (nth === 2) ? "M" : match;
});
alert(s); // "HELMO, WORLD!";


我正在尝试这样做

function ReplaceNth_n() {

Logger.log(ReplaceNth("HELLO, WORLD!", "L", "M"))

}

function ReplaceNth(strSearch,search_for, replace_with) {
   var nth = 0;
   strSearch = strSearch.replace(/search_for/g, function (match, i, original) {
   nth++;
   return (nth === 2) ? replace_with : match;
   });
  return strSearch
}


这部分失败了;更换

s = s.replace(/L/g, function (match, i, original)



strSearch = strSearch.replace(/ search_for / g,函数(match,i,original)

我尝试过变种

strSearch = strSearch.replace('/'+ search_for +'/g', function (match, i, original)

但没有得到如何做

谢谢

最佳答案

您可以使用new RegExp从变量创建正则表达式。
以下代码应该工作:

function ReplaceNth_n() {

    Logger.log(ReplaceNth("HELLO, WORLD!", "L", "M"))

}

function ReplaceNth(strSearch,search_for, replace_with) {
    var nth = 0;
    strSearch = strSearch.replace(new RegExp(search_for, 'g'), function (match, i, original) {
        nth++;
        return (nth === 2) ? replace_with : match;
    });
    return strSearch
}

ReplaceNth_n() //output 'HELMO, WORLD!'


并且,请正确设置代码段的格式...

关于javascript - 在“替换第n个子字符串Google脚本”中向RegEx添加变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49140755/

10-11 23:34