How to find all the matches?

Tags: ,



This code helps me find text between start&end words. But the search ends after the first pair found. How to find all the matches?

const file = fs.readFileSync('./history.txt', 'utf8')
const startString = '-----CompilerOutput:-stderr----------'
const endString = '-----EndCompilerOutput---------------'
const startIndex = file.indexOf(startString) + startString.length
const endIndex = file.indexOf(endString)
const between = file.slice(startIndex, endIndex)
console.log(between)

Answer

Use

const startIndex = file.match(/-----CompilerOutput:-stderr----------/gi)
const endIndex = file.match(/-----EndCompilerOutput---------------/gi)

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

https://www.w3schools.com/jsref/jsref_match.asp



Source: stackoverflow