我的目标
我想做的是类似于这样的事情:
let json_obj = {
hello: {
to: 'world'
},
last_name: {
john: 'smith'
},
example: 'a ${type}', // ${type} -> json_obj.type
type: 'test'
}
// ${hello.to} -> json_obj.hello.to -> "word"
let sample_text = 'Hello ${hello.to}!n' +
// ${last_name.john} -> json_obj.last_name.john -> "smith"
'My name is John ${last_name.john}.n' +
// ${example} -> json_obj.example -> "a test"
'This is just ${example}!';
function replacer(text) {
return text.replace(/${([^}]+)}/g, (m, gr) => {
gr = gr.split('.');
let obj = json_obj;
while(gr.length > 0)
obj = obj[gr.shift()];
/* I know there is no validation but it
is just to show what I'm trying to do. */
return replacer(obj);
});
}
console.log(replacer(sample_text));
到目前为止,这很容易做到。 但是如果$
前面有一个反斜杠((,我不想替换括号之间的东西。例如:
${hello.to}
不会被替换。
当我希望能够摆脱反斜杠时,问题就长大了。例如,我所说的转义反斜杠是:
${hello.to}
会变成:${hello.to}
\${hello.to}
会变成:world
\${hello.to}
会变成:${hello.to}
\\${hello.to}
会变成:\${hello.to}
- 等。
我试过什么?
到目前为止,我没有尝试很多事情,因为我完全不知道如何实现这一目标,因为据我所知,javascript 正则表达式中没有后视模式。
我希望我的解释方式足够清晰,可以理解,我希望有人有解决方案。
我建议您分步骤解决此问题:)
1(第一步:
简化文本的反斜杠,将""
的所有"\"
替换。这将消除所有冗余,并使令牌替换部分更容易。
text = text.replace(/\\/g, '');
2(第二步:
要替换文本的标记,请使用以下正则表达式:/[^\](${([^}]+)})/
。这将不允许前面有 \ 的令牌。例如:\${hello.to}。
下面是使用新表达式的代码:
function replacer(text) {
return text.replace(/[^\](${([^}]+)})/, (m, gr) => {
gr = gr.split('.');
let obj = json_obj;
while(gr.length > 0)
obj = obj[gr.shift()];
/* I know there is no validation but it
is just to show what I'm trying to do. */
return replacer(obj);
});
}
如果您仍有任何问题,请告诉我:)