纯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; }