ES2020 offers a new MatchAll which might be of use in this particular context.
Here we create a new RegExp, please ensure you pass 'g' into the function.
Convert the result using Array.from and count the length, which returns 2 as per the original requestor's desired output.
let strToCheck = RegExp('is', 'g')let matchesReg = "This is a string.".matchAll(strToCheck)console.log(Array.from(matchesReg).length) // 2