开放式问题。
你来定义“常见的字符串格式化需求”,并给出代码。这里举出一些例子吧
135-3425-0099
想想大家都有积累这种代码片段吧,不妨放出来让大家相互学习一下:)
阿神2017-04-10 14:26:12
number_string = {
time: function(sec) {
var min = parseInt(sec/60);
var second = parseInt(sec - min*60);
if(min < 10) min = '0'+min;
if(second < 10) second = '0'+second;
return '- '+min+':'+second;
},
fill: function(number, decimals, element) {
var number = String(number);
if(number.length < decimals)
return new Array(decimals-number.length+1).join(element)+number;
else
return number;
},
randRGBA: function() {
return ['r', 'g', 'b', 'a'].map(function() {
return parseInt(255 * Math.random());
}
},
numberFormat: function(number, decimals, dec_point, thousands_sep) {
number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
s = '',
toFixedFix = function(n, prec) {
var k = Math.pow(10, prec);
return '' + (Math.round(n * k) / k)
.toFixed(prec);
};
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n))
.split('.');
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join(dec);
},
date: function(format, utctime) {
var time = new Date(utctime);
var date = {
"M+": time.getMonth() + 1,
"d+": time.getDate(),
"h+": time.getHours(),
"m+": time.getMinutes(),
"s+": time.getSeconds(),
"q+": Math.floor((time.getMonth() + 3) / 3),
"S+": time.getMilliseconds()
};
if (/(y+)/i.test(format))
format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
for (var k in date) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1
? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
}
}
return format;
},
replace: function() {
var a = [].slice.apply(arguments), s = a.shift();
return s.replace(//{/d+/}/g, function(d) { return a[d.slice(1, -1)]; });
},
upper: function(number, unit) {
var NUM = ["〇", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "扒", "玖", "拾"],
UNI = ["仟亿", "佰亿", "拾亿", "亿", "仟萬", "佰萬", "拾萬", "萬", "仟", "佰", "拾", ""],
UNI_LEN = UNI.length;
var number = String(number), num_len = number.length;
var upper_number = number.split('').map(function(i){return NUM[i]});
if(num_len <= UNI_LEN && unit) {
return upper_number.map(function(item, i) {
return item != NUM[0] ? item+UNI[i+UNI_LEN-num_len] : item;
}).join('').replace(new RegExp(NUM[0]+'+', 'g'), NUM[0]);
}
return upper_number.join('');
}
}
其中number_string.time
格式化歌曲时间的,这个是我之前的项目里面抄过来的number_string.fill
按位补充的,这个是我现写的,以前也写过找不到了OAQnumber_string.randRGBA
随机颜色的,这个是从 @P酱 那里摘抄过来的(第二次修改整体格式的时候又稍微改了一下)。number_string.format
各种高大上格式化数字的,这个则是从 PHPJS 那里摘抄过来的。
number_string.upper
转换数字为中文大写,刚写的,在unit = true
的时候会给数字加上单位(暂时只设定对12位数有效,太高了我感觉也没必要了)。
number_string.date
是格式化时间的,来源地址。不过还是比较倾向于用 PHPJS 的这个。number_string.replace
是类似printf
这种模板替换的,来源地址。巴扎黑2017-04-10 14:26:12
抛砖引玉~
// 仅限于数字
function prefixInteger(num, length) {
return (num / Math.pow(10, length)).toFixed(length).substr(2);
}
prefixInteger(10,4)
-> "0010"
// 什么都可以传
function prefixInteger(str, length) {
return Array(length+1).join("0").split("").concat(String(str).split(""))
.slice(-length).join("");
}
prefixInteger("abc",6)
-> "000abc"
Number("111123123123.1234").toLocaleString()
-> "111,123,123,123.123"
Number("111123123123.1234").toFixed(2).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
-> "111,123,123,123.12"
"#" + prefixInteger( (Math.random() * 0xffffff).toString(16).replace(/\..*$/,"") , 6 );
-> "#02fe45"
Math.random().toString(16).substring(2); //14位
-> "52701a4e"
Math.random().toString(36).substring(2); //11位
-> "9o7egmvjw7ki6bt9"
function strrep(str,obj){
return str.replace(/\$\w+\$/gi, function(matchs) {
var returns = obj[matchs.replace(/\$/g, "")];
return typeof returns === "undefined" ? "" : returns;
});
}
strrep(
'<img src="$thesrc$" class="$theclass$">', {
"thesrc":"http://s.segmentfault.com/img/logo.png?coiweJ" ,
"theclass":"fl tc"
}
)
-> "<img src="http://s.segmentfault.com/img/logo.png?coiweJ" class="fl tc">"