如何做动态反向字符串插值



下面是我为一些代码编写的测试:

const transclude = '{fieldA}-{fieldB}-{fieldC}';
const val = {
fieldA: 'one',
fieldB: 'two',
fieldC: 'three',
};
const expected = 'one-two-three';

应该是直接的,给定对象,我想将这些值插值到transclude字符串中并得到结果。

现在,我在想一件巧妙的事情,有可能倒退吗?

const transclude = '{fieldA}-{fieldB}-{fieldC}';
const val = 'one-two-three';
const expected = {
fieldA: 'one',
fieldB: 'two',
fieldC: 'three',
};

为了从好的答案中剔除坏的答案,以下方法也需要发挥作用:

const transclude = '{fieldA}-{fieldB}-some-value-{fieldC}';
const val = 'one-two-some-value-three';
const expected = {
fieldA: 'one',
fieldB: 'two',
fieldC: 'three',
};

编辑:不得不说,我不确定为什么我在这个问题上获得了微弱的票数——在我看来,我有一个非常明确的问题要解决?如果选民认为我需要更多的关注,请发表评论,让我知道如何改进这个问题。

transclude字符串转换为具有命名捕获组的正则表达式。匹配结果的groups属性将包含所需的对象。

const transclude = '{fieldA}-{fieldB}-some-value-{fieldC}';
const transRE = new RegExp(transclude.replace(/{(.*?)}/g, '(?<$1>.*)'));
const val = 'one-two-some-value-three';
const result = val.match(transRE);
console.log(result.groups);

请注意,这并不总是产生与原始数据相同的结果,因为可能存在歧义。例如

const transclude = '{fieldA}-{fieldB}-{fieldC}';
const val = {
fieldA: 'one',
fieldB: 'two-five',
fieldC: 'three',
};

会产生one-two-five-three,但反过来会产生

result = {
fieldA: 'one-two',
fieldB: 'five',
fieldC: 'three'
}

因为CCD_ 5是贪婪的。

最新更新