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 the while condition — it will recreate the regex for every iteration and reset lastIndex.
  • Be sure that the global (g) flag is set, or lastIndex will never be advanced.
  • If the regex may match zero-length characters (e.g. /^/gm), increase its lastIndex manually each time to avoid being stuck in the same place.

Nguồn:: MDN, RegExp.prototype.exec() - JavaScript | MDN


Cập nhật lần cuối : 30 tháng 6, 2024
Tạo : 12 tháng 10, 2023