xyz
xyz

Reputation: 2300

Add variable to RegEx in Replace nth sub-string Google Script

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

Upvotes: 0

Views: 703

Answers (1)

zoryamba
zoryamba

Reputation: 345

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...

Upvotes: 1

Related Questions