Gryphon
Gryphon

Reputation: 45

Format lyrics with inline notes to readable song with chords on top

I'm struggling with what is likely a very simple regex formula.

I have a song info string with the lyrics and notes intertwined, like so.

test = "[Am]I would keep mys[F]elf [G]I would find a way"

What I'm trying to do is split the string into 2 lines, keeping the positioning of the chords, so they match up at the same position in the original string.

so the expected outcome for the above example is:

"Am              F   G                 "
"I would keep myself I would find a way"

I was able to find the following solution for removing all of the notes to give me only the lyric output:

test.replace(/\[(.*?)\]/g, "")

but I don't know enough about regex, and have been unsuccessful at finding anything similar to what I'm trying, that will return the only the notes.

I'd like to use the same method I used above for the notes, I just need assistance with the regex formula.

Thank you in advance!

Upvotes: 1

Views: 800

Answers (2)

Nikas music and gaming
Nikas music and gaming

Reputation: 1282

I found the way to format this very good, click "full page" to see the full snippet:

var string = `[Am]I would keep mys[F]elf  [G]I would find a way
[G]I would keep mys[F]elf  [Am]I would find a way`;

string = string.replace(/.+/g, "<div>$&</div>")
var song = string.replace(/\[(?<chord>\w+)\]/g, "<span>$<chord></span>");

document.body.innerHTML = song;

console.log(song);
div {
  line-height: 3em;
  position: relative;
}

span {
  position: absolute;
  line-height: 1em;
  top: 0;
}

The /.+/g matches lines and replace them with a div. The /\[(?<chord>\w+)\]/g matches the chords and replace them with a span

Upvotes: 3

K1DV5
K1DV5

Reputation: 61

Since you said you only need help on the regex: you can use regexp.exec to find details about the items you want with the pattern /\[\w+?\]/g. It will give you the matches and their indices so you can construct the notes at the right locations. One thing to note is that in order to find multiple matches, you'll have to call exec repeatedly until it returns null.

Upvotes: 0

Related Questions