Dùng regex.exec() với while dễ vào vòng lặp vô hạn
Để tránh vào vòng lặp vô hạn,
- Do not place the regular expression literal (or
RegExp
constructor) within thewhile
condition — it will recreate the regex for every iteration and resetlastIndex
. - Be sure that the global (
g
) flag is set, orlastIndex
will never be advanced. - If the regex may match zero-length characters (e.g.
/^/gm
), increase itslastIndex
manually each time to avoid being stuck in the same place.