字符串替换问题?

实现函数template()函数
template('hello ${1}, ${2} is the best ${3}',['world','javascript','language']);
//输出结果
'hello world, javascript is the best language'

function template(str,array){
    
}

想到用正则表达式提取,但不知道怎么替换到原来的字符串?

阅读 2.2k
1 个回答

使用正则表达式进行匹配,如果配置位置对应的索引在数组中没有给出则以?替代

// 定义函数 
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]));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题