【发布时间】:2021-08-06 10:27:38
【问题描述】:
我有一个从 JSON 评估的对象,如下所示:
{
"foo %s": "bar %s",
"Hello %s world %s.": "We have multiple %s %s."
}
使用这个对象和以下输入,我试图实现这样的目标:
-
foo bar-> 匹配foo %s->bar bar -
Hello foo world bar.-> 匹配Hello %s world %s.->We have multiple foo bar
到目前为止,我有以下代码适用于一个 %s,并且仅当它被空格包围时。
let str = "input here";
let a = {
"foo %s": "bar %s",
"Hello %s world %s.": "We have multiple %s %s."
},
p = str.split(" "),
result;
for (let j in p) { // loop indices
let pp = p.map(u => u); // create local array
pp[j] = "%s"; //replace index with %s
if (a[pp.join(" ")]) { // check if this is in the object
result = a[pp.join(" ")].replace("%s", p[j]); // join the array and replace %s from the result
break;
}
}
有什么想法或建议吗?
【问题讨论】:
标签: javascript json dictionary object