javascript - Is it possible to simulate string.match with a regexp.exec loop when the regexp matches the empty string? -


it common knowledge exec method regexps can used find matches in string. however, found out if regexp matches empty string loop can stuck forever

var s = '1234' var r = /()/g; var m; var = 0; while( (m = r.exec(s)) ){ console.log(i, m[0]); if(++i >= 50){ console.log("infinite loop!"); break } } 

what weird though plain string.match methods not stuck:

'1234'.match(/()/g) // gives ["", "", "", "", "", ""] 

i wonder how match method defined work differently exec loop. far way found avoid getting stuck match method involves abusing string.replace method, in horrid hack:

var matches = []; '1234'.replace(/()/g, function(m){ matches.push(m) }); 

so question is:

how match , replace return finite results when regexp matches empty string? can use same technique avoid getting stuck in exec loop?

one (icky) solution make sure it's not in same place last time:

var s = '1234' var r = /()/g; var m; var = 0; var lastposition = -1; while(m = r.exec(s)) { if(m.index === lastposition) { r.lastindex++; continue; } lastposition = m.index; console.log(i, m[0]); } 

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -