jllcode
jllcode

Reputation: 5

".Replace" in Google Apps Script

The following is a line from a example code which will extract data from a url using xpath:

xpath = xpath.replace("/html/","").replace("/tbody","","g");

(where xpath may be something like: "/html/body/table/tbody/tr[1]/table/tbody/td/tr/td[2]/a";

I don't understand why the second ".replace" can have three values? What does the "g" mean?

Is the above equivalent to the following?

xpath = xpath.replace("/html/","");

xpath = xpath.replace("/tbody","","g");

Upvotes: 0

Views: 5048

Answers (2)

Serge insas
Serge insas

Reputation: 46802

If you refer to the MDN documentation about the replace method, you will notice the syntax is as follows : enter image description here

and they describe the last parameter like below :

flags : Note - The flags argument is a non-standard Mozilla extension. A string specifying a combination of regular expression flags. The use of the flags parameter in the String.replace method is non-standard. Instead of using this parameter, use a RegExp object with the corresponding flags. The value of this parameter if it is used should be a string consisting of one or more of the following characters to affect the operation as described:

g: global match

i: ignore case

m: match over multiple lines

y: sticky

In your code you use g , meaning it's a global replacement, replacing every occurrence in the string.(note that this is non standard and that they recommend using the flag in the regular expression itself, see doc here)

I'd recommend to read the whole article as it is very clear and helps to understand what you can do with it.

Upvotes: 0

Alan Wells
Alan Wells

Reputation: 31300

It's a RegEx global modifier. Perform a global match (find all matches rather than stopping after the first match). All occurances of "/tbody" will be replaced, not just the first one.

Upvotes: 0

Related Questions