Merge pull request #575 from jareguo/v1.0

完善 formatStr
This commit is contained in:
Jare Guo
2016-04-11 10:04:38 +08:00
3 changed files with 37 additions and 31 deletions
+24 -27
View File
@@ -533,43 +533,40 @@ js.obsoletes = function (obj, objName, props, writable) {
/**
* A string tool to construct a string with format string.
* for example:
* cc.js.formatStr("a: %d, b: %b", a, b);
* cc.js.formatStr("a: %s, b: %s", a, b);
* cc.js.formatStr(a, b, c);
* @method formatStr
* @returns {String}
*/
js.formatStr = function formatStr() {
js.formatStr = function () {
var args = arguments;
var l = args.length;
if(l < 1)
return '';
if (l < 1) return '';
var REGEXP_NUM_OR_STR = /(%d)|(%s)/;
var i = 1;
var str = args[0];
var needToFormat = true;
if(typeof str === 'object'){
needToFormat = false;
var hasSubstitution = typeof str === 'string' && REGEXP_NUM_OR_STR.test(str);
if (hasSubstitution) {
var REGEXP_STR = /%s/;
for (; i < l; ++i) {
var arg = args[i];
var regExpToTest = typeof arg === 'number' ? REGEXP_NUM_OR_STR : REGEXP_STR;
if (regExpToTest.test(str))
str = str.replace(regExpToTest, arg);
else
str += ' ' + arg;
}
}
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 {
if (l > 1) {
for (; i < l; ++i) {
str += ' ' + args[i];
}
}else
str += ' ' + arg;
}
else {
str = '' + str;
}
}
return str;
};
+3
View File
@@ -227,3 +227,6 @@ window._ccsg = {
// rename cc.Class to cc._Class
cc._Class = cc.Class;
// fix cc.formatStr (#2630)
cc.formatStr = cc.js.formatStr;
+10 -4
View File
@@ -1,6 +1,4 @@
// jshint ignore: start
module('getClassName');
module('getClassName');
test('test', function() {
var Asset = function () {};
@@ -33,4 +31,12 @@ test('test', function() {
equal(cc.js.getClassName(function () {}), '', 'class name should be "" if undefined');
});
// jshint ignore: end
test('formatStr', function() {
var a = '0';
var b = 1;
var SEP = ' ';
strictEqual(cc.js.formatStr("a: %s, b: %d", a, b), 'a: 0, b: 1', 'format');
strictEqual(cc.js.formatStr('a:', null), 'a:' + SEP + 'null', 'join');
strictEqual(cc.js.formatStr("a: %s, b: ", a, b), 'a: 0, b: ' + SEP + '1', 'format and join');
strictEqual(cc.js.formatStr(null), 'null', 'neither string nor number');
});