Sunday, 8 September 2013

$0 and $1 in Regular Expression

$0 and $1 in Regular Expression

I am trying to use replace with regular expression and need some help
understanding what $1 means in this code. This code is to swap the case.
return str.replace(/([a-z])|([A-Z])/g,
function($0, $1)
{ return ($1) ? $0.toUpperCase() : $0.toLowerCase(); })
I understand in the first parameter of replace method I check if we have
lowercase or uppercase alphabet, but I do not understand how and what it
does to have the second parameter.
I understand the syntax in which if ($1) is true we execute
$0.toUpperCase(), if not we do $0.toLowerCase(). But how to decide from
what if ($1) is true? What condition does ($1) have? I think I understand
$0 is for the entire matched string. But I am confused with ($1). Thanks!

No comments:

Post a Comment