如何进行动态反向字符串插值
How to do dynamic reverse string interpolation
这是我正在为一些代码编写的测试:
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, '(?<>.*)'));
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'
}
因为.*
贪心
这是我正在为一些代码编写的测试:
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, '(?<>.*)'));
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'
}
因为.*
贪心