I have this mashup of code that I'm trying to use to transpose keys in chordpro text. The first replace should grab the text between all of the brackets. The second replace gets the chord letter and increments/decrements it.
For the most part it does transpose the chords but there are two problems.
The output is replicated by the number of chords being transposed. And second the text "{c:Chorus 1} Bless" is changed to "{c:Dhorus 1}Dbless".
var text = '{c:Intro} [D] [A] [E2/Db] [Gbm] [|] [D] [A] [|] [Esus] [E] {c:Chorus 1}Bless the [D]Lord ';
var shift = 2;
var reg = new RegExp(/\[(.*?)\]/g);
newtext = text.replace(reg, function() {
var scale = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"];
return text.replace(/[CDEFGAB]#?/g,
function(match) {
var i = (scale.indexOf(match) + shift) % scale.length;
return scale[i < 0 ? i + scale.length : i];
});
});
$('#chordpro').html(newtext);
Here is a link to a fiddle:
1 Answer 1
Try this
var text = '{c:Intro} [D] [A] [E2/Db] [Gbm] [|] [D] [A] [|] [Esus] [E] {c:Chorus 1}Bless the [D]Lord ';
var shift = 2;
var reg = new RegExp(/\[(.*?)\]/g);
newtext = text.replace(reg, function(result) {
var scale = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"];
return result.replace(/[CDEFGAB]#?/g,
function(match) {
var i = (scale.indexOf(match) + shift) % scale.length;
return scale[i < 0 ? i + scale.length : i];
});
});
$('#chordpro').html(newtext);
(The change made: Using the match from the first regular expression and matching the next regexp on that, not the original text string)