0

I am trying to add variables to my function call

The original function came from here 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!";

I am trying to do this

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 
} 

This part is failing; Replacing

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

with

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

I have tried variations on

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

But not getting how to do this

Thanks

xyz
  • 2,253
  • 10
  • 46
  • 68

1 Answers1

1

You can use new RegExp to create regular expression from variable. Following code should work:

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!'

And please, format your code sections properly...

zoryamba
  • 196
  • 11
  • It's not clear from the question whether `search_for` is supposed to be a string you want to replace, or the string used to generate a regex. (For example, `search_for="[1-9]\\d*"` for positive integers.) With this code, it will be treated as a regex. If you want `search_for` to be the actual string you're replacing, you need to escape several regex special characters in `search_for` before calling the `RegExp` constructor. Especially if `search_for` is from an untrusted source. – David Knipe Mar 06 '18 at 23:01