views:

62

answers:

2

Hi folks, I would like to get a deeper understanding of the nuances of javascript.

Take the function below:

str.replace(/(\b[^:]+):'([^']+)'/g, function ($0, param, value) {
    ret[param] = value;
});
  • Why is there a need for /g?
  • What exactly gets passed into the function?
  • Where do these values come from?

Thanks!

+5  A: 

Why is there a need for /g?

Because presumably you will have multiple pairs on the matching string, e.g. a:'b' c:'d'

What exactly gets passed into the function?

The callback function gets the whole match as the first argument, the two later arguments are the capturing groups specified on your regexp.

For example:

"a:'b' c:'d'".replace(/(\b[^:]+):'([^']+)'/g, function ($0, param, value) {
    console.log($0, param, value);
});

The callback will be executed twice, and it will show you "a:'b'" for $0, "a" for param and "b" for value on the first execution.

In the second execution -for the second match-, will show you "c:'d'" for $0, "c" for param and "d" for value.

CMS
I think it is a jQuerys' alike attribute selector? Or a js label parser? No, a Json parser ;)
Caspar Kleijne
So when a function is attached to the end of any given js function, it will act as a callback for which each element will be passed into it? And what determines the first value, second and third?
ming yeow
@Ming, no, when a function is passed as the second argument of the String `replace` method it will be called for each match encountered, that matched string will be passed as the first argument of that callback, the rest of arguments are determined by the number of capturing groups you have in your regex. [More info...](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter)
CMS
Got it: "Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global".
ming yeow
Is this a good guide to how these type of callbacks work in general?
ming yeow
+1  A: 

The g in /g stands for global. This make sure that all matches are replaced. In the absence of /g, only the first match is replaced. /i (ignore case) is another commonly used switch.

Each time the javascript engine finds a match(for your regular expression) in the string, it calls the function that you passed in with the parameters for each match.

Explained in detail here

letronje