以递归方式将占位符文本替换为变量的值

Recursively replace placeholder text with the value of a variable

本文关键字:变量 文本替换 占位符 递归 方式      更新时间:2023-09-26

今天早些时候我发布了这个问题,这个问题很快就得到了令我满意的回答。

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

这是我当前的代码示例。 完整的小部件可在此 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/