在 JS 中,我尝试从下面的代码构建一个对象。然而,我坚持使用下面的替换函数获取正则表达式命名组。
var formatters = {
'p': 'padding',
'm': 'margin',
'd': 'border', // Had to use letter "d", Becuase "b" means "bottom".
't': '-top',
'b': '-bottom',
'l': '-left',
'r': '-right'
}
var str = 'p:[p], pt:[p][t], pb:[p][b], rounded-tr:[d][t][r]-radius'
var match = str.replace(/:(?<selection>.*?)(:?,)/g, (m) => formatters[m])
// var expectedOutput = {'p':'padding', 'pt':'padding-top', 'pb':'padding-bottom', 'rounded-tr': 'border-top-right-radius'}
注意:我想做的是,从 str 变量中选择字符(从“:”到“,”),并将其替换为 formatters 值。然后将字符串设为对象。
\[([a-z])\]
var formatters = {
'p': 'padding',
'm': 'margin',
'd': 'border', // Had to use letter "d", Becuase "b" means "bottom".
't': '-top',
'b': '-bottom',
'l': '-left',
'r': '-right'
}
var str = 'p:[p], pt:[p][t], pb:[p][b], rounded-tr:[d][t][r]-radius'
var match = str.replace(/\[([a-z])\]/g, (m, p1) => formatters[p1])
console.log(match)
var expectedOutput = Object.fromEntries(match.split(', ').map(s => s.split(':')))
console.log(expectedOutput)
对于实际命名组的答案(因为这是您最终进行谷歌搜索的地方)
const formatters = {
'p': 'padding',
'm': 'margin',
'd': 'border', // Had to use letter "d", Becuase "b" means "bottom".
't': '-top',
'b': '-bottom',
'l': '-left',
'r': '-right'
};
const str = 'p:[p], pt:[p][t], pb:[p][b], rounded-tr:[d][t][r]-radius';
const output = Object.fromEntries(str.split(', ').map((s) => {
const [key, value] = s.split(':');
return [key, value.replace(/\[(?<selection>.*?)(?<end>\])/g, (...args) => {
// You receive named groups as an object in the last argument of the callback
const { selection } = args.pop();
return formatters[selection];
})]
}));
console.log(output);
// expectedOutput = {'p':'padding', 'pt':'padding-top', 'pb':'padding-bottom', 'rounded-tr': 'border-top-right-radius'}