米琪卡哇伊
使用正则表达式进行匹配,如果配置位置对应的索引在数组中没有给出则以?替代// 定义函数 var template = function(template, txtArray) { return template.replace(/\$\{([1-9][0-9]*)\}/g, function(match,idx){ var _index = parseInt(idx); if(txtArray[_index-1]) { return txtArray[_index-1]; }else{ return '?'; } })};// 测试代码console.log(template('hello ${1}, ${2} is the best ${3}', ['Miss Li', 'WildBerry', 'food']));console.log(template('${1} + ${2} = ${3}', [2, 3, 5]));console.log(template('${2}, ${4}, ${6}, ${12} ', [1,2,3,4,5,6,7,8]));