Javascript JS对象/JSON键通配符
我有一个从JSON计算的对象,如下所示:Javascript JS对象/JSON键通配符,javascript,json,dictionary,object,Javascript,Json,Dictionary,Object,我有一个从JSON计算的对象,如下所示: { “foo%s”:“bar%s”, “您好%s世界%s.”:“我们有多个%s%s。” } 通过使用此对象和以下输入,我试图实现以下目标: foo-bar->匹配foo%s->bar Hello foo world bar.->匹配Hello%s world%s.->我们有多个foo bar 到目前为止,我有以下代码,它适用于一个%s,并且仅当它被空格包围时 let str = "input here"; let a = {
{
“foo%s”:“bar%s”,
“您好%s世界%s.”:“我们有多个%s%s。”
}
通过使用此对象和以下输入,我试图实现以下目标:
->匹配foo-bar
->foo%s
bar
->匹配Hello foo world bar.
->Hello%s world%s.
我们有多个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;
}
}
有什么想法或建议吗?您可以将对象转换为,然后 单个已定义替换操作的示例:
console.log('Hello foo world bar.'.replace(/^Hello(.*)world(.*)bar\.$/,'We have multiple$1$2.'))
//输出:我们有多个foo-bar。
在这里,我们基本上匹配整个字符串-如果它匹配模式,整个内容将被替换
如您所见,要实现这一点,您需要将“Hello%s world%s.”
转换为/^Hello(.*?)world(.*?)$/
(使用(.*?
定义包含任何字符的非贪婪捕获组)和“我们有多个%s%s.”
转换为“我们有多个$1$2”。
(其中,$x
指的是x
-th捕获组的内容)
所以你可以有这样一个函数:
函数替换模板(str,模板){
//此helper函数将转义任何具有特殊字符的字符
//在regexp中的含义不同。$&是作为一个整体的匹配项,因此它替换
//这些角色中的每一个都有自己的反冲。
const escapeRegExp=s=>s.replace(/[.*+?^${}()|[\]\\]/g,'\\$&'))
用于(对象项(模板)的常量[模板,替换]){
//我们从模板创建一个regexp,将每个%s替换为(.*),并将其包装
//在^和$(字符串的开始/结束)中,并转义所有其他特殊字符。
const re=new RegExp(“^”+escapeRegExp(模板)。替换(/%s/g,”(.*))+“$”)
如果(重新测试(str)){
//要获取字符串替换方法右侧的正确字符串,
//我们必须将替换字符串中的每个%s替换为$1、$2、$3等
//还可以将单个$符号替换为$$,因为$具有特殊含义,如图所示
//然后我们可以调用实际的replace并返回结果
//正如刚才所解释的那样,我们必须在替换中转出$
//四个$signs,最后得到两个。
设i=1//在以下$x的替换操作中用作计数器
常量重新替换=替换
.替换(/\$/g,$$$)
.replace(/%s/g,()=>'$'+i++)//通过使用函数,我们可以使$x成为动态的
返回str.replace(重新,重新替换)
}
}
返回str
}
常量模板={
'foo%s':'bar%s',
“您好%s世界%s.”:“我们有多个%s%s.”
}
log(replaceTemplates('foo-bar',templates))//输出:bar
log(replaceTemplates('Hello foo world bar',templates))//输出:我们有多个foo bar。