1 回答

TA貢獻(xiàn)1998條經(jīng)驗(yàn) 獲得超6個(gè)贊
使用正則表達(dá)式進(jìn)行匹配,如果配置位置對(duì)應(yīng)的索引在數(shù)組中沒(méi)有給出則以?替代
// 定義函數(shù)
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 '?';
}
})
};
// 測(cè)試代碼
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]));
添加回答
舉報(bào)