#javascript #node.js
#javascript #node.js
Вопрос:
Этот код помогает мне находить текст между начальными и конечными словами. Но поиск заканчивается после первой найденной пары. Как найти все совпадения?
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)
Комментарии:
1. @angel.bonev дал отличный совет. Другим вариантом было бы включить прежний индекс в последующие вызовы .indexOf внутри цикла
Ответ №1:
Используйте
const startIndex = file.match(/-----CompilerOutput:-stderr----------/gi)
const endIndex = file.match(/-----EndCompilerOutput---------------/gi)
Ссылка: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions