我用字符串中的单词列表替换了所有字符。
我使用String.prototype.replaceAll(list)
替换了所有已定义的选项。主要问题是字典中单词G
的最后一个键替换字符串中的所有字符。我有代码(JSfiddle):
String.prototype.replaceL = function(obj) {
let retStr = this;
for (let x in obj) {
retStr = retStr.replace(new RegExp(x, 'g'), obj[x]);
}
return retStr;
};
let str = 'Gm Gmadd9 Cm Cm7 Eb Cm6 D D Gm Eb Cm7 D7 Gm Eb Cm7 D7 Gm Gm+ Gm Gm Gm+ Fsus4 F Fsus4 Eb Ebadd11+ F Fadd11 D D Dadd9- D Eb Ebadd11+ F F Gm Gmadd9 Eb Eb Cm7 Cm6 D D Fsus4 F F Gm Gm+ Gm Gm Gm+ Gm Gm/F Gm Fsus4 F Fsus4 F Gmsus4 Gm F Bbmaj Bb D D7 Gmsus4 Gm';
let resMatch = str.match(/[A-H]b?#?/g);
let oRep = {
'A': 'Bb',
'Ab': 'A',
'A#': 'B',
'B': 'C',
'Bb': 'B',
'C': 'C#',
'C#': 'D',
'D': 'Eb',
'D#': 'E',
'E': 'F',
'Eb': 'E',
'F': 'F#',
'F#': 'G',
'G': 'Ab',
'G#': 'A',
'Gb': 'E',
'H': 'C',
};
init.textContent = str;
res.textContent = str.replaceL(oRep);
body {
font-family: Consolas;
}
span {
display: block;
font-weight: bold;
padding: 10px 0;
}
<span>string of chords:</span>
<div id="init"></div>
<span>string of transpose chords:</span>
<div id="res"></div>