之前cocos2dx-js是沒有格式化字符串的API的,以前自己還手動寫了一個。
現在發現有了,做法和我之前用的正則表達式去替換沒什麼大的差異。
用法:
/**
* A string tool to construct a string with format string.
* for example:
* cc.formatStr("a: %d, b: %s", a, b);
* cc.formatStr(a, b, c);
* @returns {String}
*/
引擎API:
cc.formatStr = function(){
var args = arguments;
var l = args.length;
if(l < 1)
return "";
var str = args[0];
var needToFormat = true;
if(typeof str === "object"){
needToFormat = false;
}
for(var i = 1; i < l; ++i){
var arg = args[i];
if(needToFormat){
while(true){
var result = null;
if(typeof arg === "number"){
result = str.match(/(%d)|(%s)/);
if(result){
str = str.replace(/(%d)|(%s)/, arg);
break;
}
}
result = str.match(/%s/);
if(result)
str = str.replace(/%s/, arg);
else
str += " " + arg;
break;
}
}else
str += " " + arg;
}
return str;
};
大致思路:逐個檢查需要格式化的類型(number或者string),然後用正則去按逐個匹配,match有返回則說明檢測到“%d”,”%s”然後用提供的args去替換。