gpt4 book ai didi

javascript - 用变量的值递归替换占位符文本

转载 作者:行者123 更新时间:2023-12-02 15:04:52 24 4
gpt4 key购买 nike

今天早些时候我发布了this question ,很快就得到了令我满意的答复。

自从出现新需求以来,我现在需要用它的值递归地替换变量占位符

这是我当前的代码示例。完整的小部件可在 this Pastebin 中找到。 -

$.widget('custom.contents', {

options : {

singleID : 'content-{index}',
linkID : 'link_to_{singleID}'

}, // options

_create : function(){

console.log(this._getOption(25, 'linkID'));

}, // _create

_getOption : function(index, option){

var t = this; // The object

var optionValue = this.options[option].replace(/{(.+?)}/g, function(_, name){
return name === 'index' ? index : t.options[name];
});

return optionValue;

} // _getOption

});

如果我要包含 console.log(this._getOption(25, 'linkID')); 输出值将为 link_to_foobar-{index}

在返回该值之前,我想递归地运行 _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

实例:https://jsfiddle.net/7ng1bhda/1/

关于javascript - 用变量的值递归替换占位符文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35179047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com