vendredi 31 juillet 2015

Understanding some JavaScript with a RegExp

I have the following js code

var regex = new RegExp('([\'"]?)((?:\\\\\\1|.)+?)\\1(,|$)', 'g'),
key = regex.exec( m ),
val = regex.exec( m );

I would like to understand it. In particular:

  • why there are all those backslash in the definition of the RegExp? I can clearly see that \\1 is a reference to the first saved element. Why in a new RegExp using ' and not " we need to use \\1 and not simple \1?

  • why there is a comma between the two definitions of key and val? I may guess that it depends on the "instances" finded using "g", but it is not very clear anyway to me.

I tried to execute the code with

m = 'batman, robin' 

and the result is pretty a mess, and I cannot really explain it very well.

Aucun commentaire:

Enregistrer un commentaire