Fragmented Thought

Javascript Global Regex Match

By

Published

Lance Gliser

Heads up! This content is more than six months old. Take some time to verify everything still works as expected.

I needed to do a case insensitive, multiline, global regex (/img) over some html. The matches kept coming back wrong using $.each() and Mozilla's directions. The while loop on the Mozilla docs site didn't work for me, every time it returned match as "true." That's no help, of course. So, a do while loop instead, and all is well.

var regex = /./gim; var matches = []; var match; match = regex.exec(text); while (match instanceof Array) { matches.push(match); match = regex.exec(text); }