I\'m trying to parse an AJAX response and get the id of the body tag. I can\'t do this via jQuery, though, because jQuery can\'t emulate a DOM response for a body tag.
You should either pass a string to the constructor for regexen, or use the regex literal syntax, but not both.
var bodyIDregex = /<body[^>]*id=["'](.*?)["']>/gi
or
var bodyIDregex = new RegExp("<body[^>]*id=[\"'](.*?)[\"']>","gi")
Update:
As you have correctly identified in your answer, the problem stems from the fact that the regex search continues from the position of the last character in the previous match. One way to correct this is to reset lastIndex
, but in this case this is not required, since you only need to match against the string once:
var bodyIDregex = /<body[^>]*id=["'](.*?)["']>/gi,
bodyID = bodyIDregex.exec(html);
//bodyID is now the array, ["<body id="test">asdf</body>", "test"]
alert(bodyID[1]);
//alerts the captured group, "test"
Apparently, when you call (RegExp object).match(string), it increments a property of the RegExp object called lastIndex. I am not completely familiar with how the RegExp object works, but this causes an issue when trying to call the exec() method later.
The solution, apparently, is to reset lastIndex to zero.
var html = '<html><body id="test">asdf</body></html>';
var bodyIDregex = /<body[^>]*id=["'](.*?)["']>/gi,
matched = html.match(bodyIDregex);
// Reset lastIndex
bodyIDregex.lastIndex = 0;
var bodyID = bodyIDregex.exec(matched[0]);
alert(bodyID.length);
bodyID = bodyID[1];
document.write(bodyID); // writes test