2

Reading this discussion, I didn't understand what this means:

 $1X$2 

Simply X?

And about this other code:

 str = str.replace(/(<script.*?>)(.*)(?=<\/script>)/gi, function(x,y,z) {return y+z.replace(/a/gi,'Z')}) 

Here is what I didn't understand:

  • ?=
  • how does function(x,y,z) works? i.e. from where it take x, y and z?

I'll be very grateful if someone could explain in a clear way this code.

1

3 Answers 3

4

The $1 and $2 are referencing the captured sub-expressions (which are delimited by parentheses ()) from the regular expression in the previous argument to .replace().

The ?= is a positive lookahead. http://www.regular-expressions.info/lookaround.html

The function(x, y, z) is an anonymous function expression that does a similar thing to referencing $1 and $2, but it stores them in variables instead.

Sign up to request clarification or add additional context in comments.

Comments

4
  1. The string "$1X$2" used as the second argument to a .replace() call includes references to groups from the regular expression first argument. Groups — portions of the regular expression in parentheses — collect the characters they match for use later. The substrings "$1" and "$2" mean, "whatever was matched by the group 1" (or group 2).

  2. When the second argument to a call to .replace() is a function, JavaScript passes the match information to the function as arguments. The first argument is always the entire match. The subsequent arguments are the matched groups.

Thus:

alert("hello world".replace(/(ell)(o w)/, "$2$1"); // alerts "ho wellorld" 

Comments

4

This is all about capturing groups. ( and ) capture everything between, so you can later access substrings of your match.

$1 refers to the first captured group, $2 to the second one (so first and second pair of parentheses, respectively). ($0 would refer to the whole match.)

The variant with the callback function does the same, but here the variables x, y and z are filled with the captured groups (corresponding to $0, $1 and $2 respectively).

Finally ?= opens a lookahead. That asserts that this possition in the match is followed by <\/script> without actually advancing the regex engine in the matched string and also without including this part in the match.

Comments