Jannuzzo
Jannuzzo

Reputation: 169

Replace all occurencis of a substring except from strings between "

I have this code which replaced all the occurences of a certain substring inside the string code.

while (codecall= code.indexOf(mname) != -1) {
      position= codecall;
      code= code.replace(mname, "teach_subfun");
      i--;
}

This works good to me except the fact that the string code is actually representing some Javascript code I have to evaluate. Let's take an example of my problem. Let's say these are the variables values:

mname= "foo";
code= "document.write ('this foo must not be replaced'); foo (n);";

What i get with my code is:

mname= "foo";
code= "document.write ('this teach_subfun must not be replaced'); teach_subfun (n);";

What I'd like to obtain is:

mname= "foo";
code= "document.write ('this foo must not be replaced'); teach_subfun(n);";

is there a simple way to do it? maybe with RegExp?

Upvotes: 2

Views: 82

Answers (2)

António Almeida
António Almeida

Reputation: 10087

Assuming that your code is well formatted (correct number of quotes):

Demo at jsFiddle

mnameA = /foo/g;
mnameB = "teach_subfun";
code= "document.write ('this foo must not be replaced'); foo(n);";

codeRep = code.split(/'|"/).map(function (e, i){
    return i % 2 ? e : e.replace(mnameA, mnameB);
}).join("");

How does this works:

If you split by ", strings will by always at the odd indexes (i % 2 == 1) of the generated array (unless your code starts with a string), so the map function is going to replace all the foo's (/foo/g, g is for all) within each even element of the array.

Upvotes: 2

Rob
Rob

Reputation: 11788

A quick and dirty way would be to not only look for foo but for foo ( or even for ; foo ( and then replace it accordingly:

code.replace(mname, "; teach_subfun (");

Upvotes: 0

Related Questions