javascript - 字符串替换问题?
大家讲道理
大家讲道理 2017-04-11 13:14:40
[JavaScript讨论组]

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

function template(str,array){
    
}

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

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(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]));
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号