IE8 is not recognizing my regular expression

后端 未结 2 610
故里飘歌
故里飘歌 2020-12-21 11:07

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.

2条回答
  •  长情又很酷
    2020-12-21 11:38

    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 = 'asdf';
    
    var bodyIDregex = /]*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
    

提交回复
热议问题