开发者

What exactly happens in this javascript sequence?

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

Take the function below:

str.replace(/(\b[开发者_JAVA百科^:]+):'([^']+)'/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!


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜