javascript - 字符串替换问题?

查看:68
本文介绍了javascript - 字符串替换问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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

function template(str,array){
    
}

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

解决方案

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

// 定义函数 
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]));

这篇关于javascript - 字符串替换问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆