The lastIndex property in JavaScript regexes

A regular expression has the lastIndex property. It contains the position from which the next call of the exec method will start searching. That is, with each new method call, this property will change its value. Let's look at an example:

let str = '12 34 56'; let reg = /\d+/g; console.log(reg.lastIndex); // initial value is 0 let res; while (res = reg.exec(str)) { console.log(res); // [12], [34], [56] console.log(reg.lastIndex); // 2, 5, 8 }

The advantage of lastIndex is that it can be not only read, but also changed, starting the search from a given position. See an example:

let str = '12 34 56'; let reg = /\d+/g; reg.lastIndex = 2; let res = reg.exec(str) console.log(res); // [34]

Given the following string:

let str = '12:37 15:48 17:59';

Find in it all substrings with the time, starting from the fifth character.

enru