Home > front end >  which approach to create browser extension that parses html and converts it into chordpro
which approach to create browser extension that parses html and converts it into chordpro

Time:12-21

I'd like to build a firefox extension which parses some fragements of a website that contains a song. The goal is to turn a music chord written in HTML e.g. any <span >This is<span >Em<sup>7</sup></span>an example</span> into e.g. This is[Em7] an example (that's chordpro formatting).

I did some tutorials on how to create firefox extensions but I have to be honest that I don't know javascript that well. All I know is that it is capable of doing so. That's why I wanted to ask you guys, what an appropriate approach would be? The song I want to parse consists of several elements described before. The goal in the end is to save the formatted song in a chordpro file (txt would also be okay).

CodePudding user response:

Use a proper HTML parser like DOMParser, then you can easily use Element.replaceWith() to construct the desired output

const formatter = (html) => {
  const doc = new DOMParser().parseFromString(html, "text/html");
  doc.querySelectorAll(".chord").forEach(elChord => {
    elChord.replaceWith(`[${elChord.textContent}]`);
  })
  doc.querySelectorAll(".beginLine").forEach(elLine => {
    elLine.replaceWith(`${elLine.textContent}`);
  })
  return doc.body.textContent.trim().replace(/\n \s /g, "\n");
};


const scrapedHTML = `
  <span >This is <span >Em<sup>7</sup></span> an example</span>
  <span >and how <span >A<sup>13</sup></span> to do it?!</span>
`;
const formatted = formatter(scrapedHTML);
console.log(formatted);

  • Related