I'm trying to use regular expressions instead of string functions to return a value belonging to a given name in document.cookie.
First, traditionally I did this and it, of course, works fine:

function readCookie(name)
{

var c=document.cookie;
var pairs=c.split(";");
for(var i=0; i< pairs.length; i++)
{
var p=pairs[i].split("=");
while(p[0].charAt(0)==' '){p=p.substring(1,p.length);}
if(p[0]==name){return p[1];}
}

return false;
}

So far so good..,but I want to use back referencing to do the same,so I tried this:
function readCookie(name)
{


var str= name +"="+"([^;]+);";
/*intended meaning:concatanate the string value in the variable called name with = and a regular expression pattern that is targeting the value part after the given name.
*/
/*Then create a new RegExp object with this string, because I don't know
how I could use the name variable in a regular literal.. Can I? I know the RegExp object takes a string with the pattern as its first argument*/
var reg= new RegExp(str,"gi");
/*and use the part in bracket to back reference to the interesting value part*/
if(reg.test(c))
{
return "$1";
}
else{ return false;}
}
.. but it's all wrong. Can you tell me where the logic above fails?