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
RegExpconstructor) within thewhilecondition — it will recreate the regex for every iteration and resetlastIndex. - Be sure that the global (
g) flag is set, orlastIndexwill never be advanced. - If the regex may match zero-length characters (e.g.
/^/gm), increase itslastIndexmanually each time to avoid being stuck in the same place.