0

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:

https://jsfiddle.net/woemL2kd/11/

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, I knew it was a logic problem. I just wasn't seeing it! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.