Javascript string exec weird behavior

have funciton in my object that gets called regularly.

parse : function(html)
{
    var regexp = /...some pattern.../
    var match = regexp.exec(html);
    while (match != null)
    {
        ...
        match = regexp.exec(html);
    }
    ...
    var r = /...pattern.../g;
    var m = r.exec(html);
}

with unchanged html mreturns null one after another. let's say

parse(html);// ok
parse(html);// m is null!!!
parse(html);// ok
parse(html);// m is null!!!
// ...and so on...

is there any index or somrthing that should be reset to html... I'm really confused. Why matchalways returns the correct result?

+3
source share
2 answers

This is common behavior when dealing with patterns that have a global flag g, and you use the execor methods test.

RegExp lastIndex, , lastIndex , 0.

: , RegExp :

, , :

& sect; 7.8.5 -

...

, . ; .

....

:

function createRe() {
  var re = /foo/g;
  return re;
}

createRe() === createRe(); // true, it the same object

, , " , === , ", :

/foo/ === /foo/; // always false...

, IE, RegExp.

+3

, ,

var r = /...pattern.../g;
var m = r.exec(html);
r.lastIndex=0;

.

+1

Source: https://habr.com/ru/post/1744872/


All Articles