Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 用变量值递归替换占位符文本_Javascript_Jquery_Variables - Fatal编程技术网

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-是否存在性能差异,还是个人偏好?@DavidGard
match
用于提取字符串,
test
用于检查字符串是否包含模式。@DavidGard如果键
索引
已修复,我为您效劳。让我知道它是如何工作的。
opt.match
返回一个匹配数组或null。然而@Tushar是正确的,作为
模式更好。test
-答案更新
opt.match(模式)
==>
模式。test(opt)
@Tushar-是否存在性能差异,还是个人偏好?@DavidGard
match
用于提取字符串,
test
用于检查字符串是否包含模式。@DavidGard如果键
index
已修复,我为您准备好了。让我知道它是如何工作的。
opt.match
返回一个匹配数组或null。然而@Tushar是正确的,它作为
模式更好。测试
-答案更新