const fs = require('fs');
const fileName = 'songs/Sister Golden Hair.txt';
fs.readFile(fileName, 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
// Split the file into lines
const lines = data.split('\n');
// Regular expression to match chords within square brackets
const chordRegex = /\[([^\]]+)\]/g;
// Iterate through each line and extract chords and lyrics
for (let line of lines) {
// Extract chords
const chords = [];
let chordMatch;
let lastIndex = 0;
while ((chordMatch = chordRegex.exec(line)) !== null) {
const chord = chordMatch[1];
const index = chordMatch.index;
// Calculate spacing
const spacing = ' '.repeat(index - lastIndex);
chords.push(spacing + chord);
lastIndex = index + chord.length;
}
// Remove chords from the line
const lyrics = line.replace(chordRegex, '').trim();
// Display chords above lyrics
console.log(chords.join(' ') + '\n' + lyrics);
}
console.log("DONE");
});
Current output:
Intended output:
Here is the chordpro file. I think the issue is that the code is not compensating for the length of the chord and adds to many spaces.
ChordPro example:
Thanks!



If you are ok with using a couple of string.splits instead of regex, have a look.
Edit - added code to add space to lyrics if chords part is too big to fit.