I was wondering how would one create a javascript function for transposing music chords.
Since I don\'t expect everyone to be a musician here, I\'ll try to explain how i
Define your keys with an object:
var keys = ["A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"];
Parse your chord with a regular expression:
var matches = /([A-G]#?)([^\/]*)(?:\/([A-G]#?))?/.exec(chord);
var key = matches[1];
var descriptor = matches[2];
var bass = matches[3];
Do a little math to get the new key:
var newKey = keys[(keys.indexOf(key) + transpose) % keys.length];
var newBass = keys[(keys.indexOf(bass) + transpose) % keys.length];
Put it all back together again:
var newChord = newKey + descriptor;
if (newBass) {
newChord += "/" + newBass;
}
return newChord;