Javascript 用变量值递归替换占位符文本
今天早些时候我发了一篇帖子,很快得到了满意的回复 自从一个新的需求出现以来,我现在需要用它的值递归地替换一个变量占位符 下面是我目前的代码示例。完整的小部件在中提供- 如果我要包括Javascript 用变量值递归替换占位符文本,javascript,jquery,variables,Javascript,Jquery,Variables,今天早些时候我发了一篇帖子,很快得到了满意的回复 自从一个新的需求出现以来,我现在需要用它的值递归地替换一个变量占位符 下面是我目前的代码示例。完整的小部件在中提供- 如果我要包括console.log(this.\u getOption(25,'linkID')输出值将是link_to_foobar-{index} 在返回该值之前,我希望递归地运行\u getOption()函数,以确保替换{}中包含的所有值 如何实现这一点?您可以使用您的模式执行循环,在继续匹配的同时,继续执行替换: _ge
console.log(this.\u getOption(25,'linkID')代码>输出值将是link_to_foobar-{index}
在返回该值之前,我希望递归地运行\u getOption()
函数,以确保替换{}
中包含的所有值
如何实现这一点?您可以使用您的模式执行循环,在继续匹配的同时,继续执行替换:
_getOption = function(index, option){
var opt = this.options[option];
var pattern = /{(.+?)}/g;
while(pattern.test(opt)){
opt = opt.replace(pattern, function(_, name){ // Search for all instances of '{(.+?)}'...
return name === 'index' ? index : t.options[name]; // ...Replace all instance of '{(.+?)}' with the value of the associated variable
});
}
return opt;
} // _getOption
实时示例:您可以使用您的模式执行循环,在继续匹配的同时,继续执行替换:
_getOption = function(index, option){
var opt = this.options[option];
var pattern = /{(.+?)}/g;
while(pattern.test(opt)){
opt = opt.replace(pattern, function(_, name){ // Search for all instances of '{(.+?)}'...
return name === 'index' ? index : t.options[name]; // ...Replace all instance of '{(.+?)}' with the value of the associated variable
});
}
return opt;
} // _getOption
实时示例:您能否添加实时演示。当函数被称为\u getOption()
时,函数中的这个是窗口对象。@Tushar我想我们可以安全地假设选项和函数\u getOption
都在同一个对象中;)@Tushar-它们在同一个对象中,我正在调整我的示例以使其更加明显…@Tushar-示例已更新,我已将完整代码添加到了。能否添加实时演示。当函数被称为\u getOption()
时,函数中的这个
是窗口
对象。@Tushar我想我们可以安全地假设选项
和函数\u getOption
都在同一个对象中;)@Tushar-它们在同一个对象中,我正在调整我的示例以使其更加明显…@Tushar-示例已更新,并且我已将完整代码添加到了。opt.match(pattern)
==>pattern.test(opt)
@Tushar-是否存在性能差异,还是个人偏好?@DavidGardmatch
用于提取字符串,test
用于检查字符串是否包含模式。@DavidGard如果键索引
已修复,我为您效劳。让我知道它是如何工作的。opt.match
返回一个匹配数组或null。然而@Tushar是正确的,作为模式更好。test
-答案更新opt.match(模式)
==>模式。test(opt)
@Tushar-是否存在性能差异,还是个人偏好?@DavidGardmatch
用于提取字符串,test
用于检查字符串是否包含模式。@DavidGard如果键index
已修复,我为您准备好了。让我知道它是如何工作的。opt.match
返回一个匹配数组或null。然而@Tushar是正确的,它作为模式更好。测试-答案更新