Skip to content
Advertisement

How to find all the matches?

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)

Advertisement

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement