纯JS实现格式化含通配符的消息

直接上代码~

/**
 * format message with given parameters array.
 * eg: when call 
 *            formatMsg("Hello,{0}!",new Array("world"))
 *     we get "hello,world!"
 
 * @param {Object} message
 * @param {Object} parametersArray
 */
function formatMsg(message,parametersArray){
    var matchesArray = message.match(/\{(\d+)\}/g);
    
    var replacedMsg=message;
    for (var i=0; i<matchesArray.length; i++) {
        replacedMsg = replacedMsg.replace(matchesArray[i], parametersArray[i]);
    }
    return replacedMsg;
}

 

posted @ 2013-05-30 11:03  yejg1212  阅读(1925)  评论(0编辑  收藏  举报