javascript - 如何将 Javascript 反向引用传递给键或函数?

标签 javascript regex backreference

<script type='text/javascript'>

 // I have template and info
 var img_template = "<img src='{src}' width='{width}' height='{height}' title='{title}' />";
 var img_info = {
  src : 'http://myimage.com/img.jpg',
  width: '100px',
  height: '100px',
  title: 'My Image'
 }

 // I want to put info to template but It's not work.
 // How should I do ?
 var my_image = img_template.replace(/{(.+?)}/g, img_info['$1']);

</script>

最佳答案

使用函数进行替换:

<script type='text/javascript'>
 var img_template = "<img src='{src}' width='{width}' height='{height}' title='{title}' />";
 var img_info = {
  src : 'http://myimage.com/img.jpg',
  width: '100px',
  height: '100px',
  title: 'My Image'
 }

 var my_image = img_template.replace(/{(.+?)}/g, function(a,b){
      return img_info[b];
 });
</script>

关于javascript - 如何将 Javascript 反向引用传递给键或函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4377904/

相关文章:

javascript - 在javascript中提取由两个不同短语分隔的大字符串内部的字符串

python - re.sub 中反向引用中的大小写匹配

javascript - 如何将数组中的 json 插入 highcharts?

javascript - 从 Dropbox 访问字体时出现 CORS 错误

javascript - 在扩展的内容脚本中使用 document.write 加载脚本

regex - 为什么#match返回正确的结果,但#scan只找到一个字母?

regex - Ansible Lineinfile - 使用反向引用时转义单引号

javascript - 菜单 css 和 javascript

javascript - 正则表达式 - 将用户输入限制为 0-128

javascript - 在 JavaScript 中创建正则表达式的问题