0

For example i want to get the first character of a string using the '^' meta char. This will make the following code crash because exec() never returns null. Is there a way to make it works without changing the regex ? (At least not crash ?)

const regexp = /^/g;
const str = 'Lorem ipsum';
let regexMatches = [];

 while ((matches = regexp.exec(str)) !== null) {
   regexMatches.push({str: matches[0], index: regexp.lastIndex});
 }
  • 1
    `^` doesn't match the first character! It matches the beginning of the string (or a line with multi-line (`m`) modifier) – phuzi Mar 12 '20 at 12:22
  • See also https://stackoverflow.com/a/21436580/1048572 – Bergi Mar 12 '20 at 12:32

1 Answers1

1

Save the lastIndex from the previous match. If it doesn't change, break out of the loop.

let prevIndex = -1;
while ((matches = regexp.exec(str)) !== null) {
    if (regexp.lastIndex == prevIndex) { // no movement
        break;
    }
    regexMatches.push({str: matches[0], index: regexp.lastIndex});
    prevIndex = regexp.lastIndex;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    Don't break, but rather advance by one position. There might be more matches elsewhere. – Bergi Mar 12 '20 at 12:34