Open zhangxinxu opened 5 years ago
题目1
//zxx: 如果原本格式就有空格会有问题
var bankCode = '6222081812002934027';
console.log(bankCode.replace(/(\d{4})/g, '$1 '));
题目2
方法1
var numberCode = '5702375';
console.log(Number(numberCode).toLocaleString());
方法2
// zxx: 此方法小数无效
var numberCode = '5702375';
console.log(numberCode.replace(/(\d)(?=(\d{3})+$)/g, '$1,'));
题目3
var filesize = 2837475;
function formatterFilesize(size, n){
var K = 1024;
var M = 1024 ** 2;
var G = 1024 ** 3;
if(size < M){
return roundNumber(size / K, n) + 'K';
}else if(size < G){
return roundNumber(size / M, n) + 'M';
}else{
return roundNumber(size / G, n) + 'G';
}
}
function roundNumber(number, n=2){
return Math.round(number * Math.pow(10, n)) / (Math.pow(10, n));
}
console.log(formatterFilesize(filesize))
console.log(formatterFilesize(475)); // size < 1K
console.log(formatterFilesize(4475)); // size < 1M
console.log(formatterFilesize(5548475)); // 1M <= size < 1G
console.log(formatterFilesize(6568358465)); // 1G <= size
// 1. js 处理
// zxx: 你这个方法我没跑起来,a改成arr结果也不对
var bankCode = "6222081812002934027";
var arr = [4,4,4,4,3];
var newCode = "";
arr.forEach(item => {
//a指的是bankCode
newCode += item == arr[arr.length-1] ? a.slice(0,item) : a.slice(0,item)+" ";
})
bankCode = newCode
//正则处理
var bankCode = "6222081812002934027";
bankCode = bankCode.replace(/(\d{4})/g, '$1 ')
// zxx: 小数无效
function moneySlice(money){
//格式不正确抛出异常
if(isNaN(money)) return Error('请传入纯数字');
let moneys = money ? money.toString() : money;
return moneys.replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
首先说下获取回来的文件大小单位都是比特 且 1024B = 1K 1024K = 1M 1024M = 1G; 测试用例 var test = [100,1050,2837475,28374756565];
function unit(num){ var K = 1024, M = 1024 1024 , G = 1024 1024 * 1024; if(num > G) return (num / G ).toFixed(2) + 'G' ; if(num > M) return (num / M).toFixed(2) + 'M'; return (num / K).toFixed(2) + 'K' ; } console.log(unit(filesize)); 执行测试用例打印 test.forEach(=>{ console.log(unit()); })
var card_num = '6222081812002934027'
var result1 = card_num.replace(/(\d{4})/g, '$1 ')
console.log(result1)
//zxx: 小数有问题
var numberCode = '5702375'
var result2 = numberCode.replace(/(?!^)(?=(\d{3})+$)/g, ',')
console.log(result2)
// zxx: 最好取几位小数,最好单位大写
var filesize = 2837475
function normalizeFilesize(filesize) {
if (typeof filesize != 'number' || filesize < 0) {
throw Error('参数不合法')
}
var gvalue = filesize / 1024 / 1024 / 1024
if (gvalue > 1) {
return gvalue + 'g'
}
var mvalue = gvalue * 1024
if (mvalue > 1) {
return mvalue + 'm'
} else {
return (mvalue * 1024) + 'k'
}
}
console.log(normalizeFilesize(filesize))
1.
//zxx: 题目不是这个意思
var bankCode = '6222081812002934027';
var result = bankCode.split('').join(' ');
console.log(result);
2.
// zxx: 没必要取整
var numberCode = '5702375';
var result = parseInt(numberCode).toLocaleString();
console.log(result);
3.
//zxx: 只取一位小数有点少
var filesize = 2837475;
function convertFileSize(fileSizeInBytes) {
var i = -1;
var byteUnits = [' KB', ' MB', ' GB'];
do {
fileSizeInBytes = fileSizeInBytes / 1024;
i++;
} while (fileSizeInBytes > 1024 && i < 2);
return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
};
var result = convertFileSize(filesize);
console.log(result);
//第一题
// zxx: 棒棒哒,还差一点
var bankCode = "6222081812002934027";
console.log(bankCode.replace(/(?!^)(?=(\d{4})*\d{3}$)/g,"$& "))
//第二题
//zxx: 小数的问题
var numberCode = "5702375";
console.log(numberCode.replace(/(?!^)(?=(\d{3})+$)/g,"$&,"));
//第三题
//zxx: 最好取个几位小数
var filesize = 2837475;
console.log(formatter(filesize));
function formatter(filesize){
var K = 1024,
M = 1024 **2 ,
G = 1024 **3;
if(filesize > G) return (filesize / G ) + 'G' ;
if(filesize > M) return (filesize / M) + 'M';
return (filesize / K) + 'K' ;
}
1.
// zxx: 如果原本有空格,这个方法很危险
var convertBankCode = function(val) {
return (val === null || val === undefined ? '' : (val + '')).substring(0,19).replace(/(.{4})/g,'$1 ');
};
console.log(convertBankCode('6222081812002934027'));
2.
var convertNumber = function(val) {
val = +(val === null || val === undefined ? '' : (val + ''));
return isNaN(val) ? NaN : val.toLocaleString();
};
console.log(convertNumber('5702375'));
console.log(convertNumber('57023.75'));
console.log(convertNumber('570a75'));
3.
var convertFileSize = function(val) {
if (val === null) {
return val;
} else if (isNaN(val)) {
return NaN;
} else {
var kbSize = 1024;
var mbSize = 1024 * 1024;
var gbSize = 1024 * 1024 * 1024;
if (val < mbSize) {
return Math.round(val * 100 / kbSize) / 100 + 'K';
} else if (val < gbSize) {
return Math.round(val * 100 / mbSize) / 100 + 'M';
} else {
return Math.round(val * 100 / gbSize) / 100 + 'G';
}
}
};
console.log(convertFileSize(1000));
console.log(convertFileSize(1030));
console.log(convertFileSize(1024 * 1040));
console.log(convertFileSize(1024 * 1024 * 1050));
//zxx: 原本有空格就凉凉了
var bankCode = "6222081812002934027";
var result = bankCode.split('').reduce((a, b) => {
return a.replace(/\s/g, '').length % 4 === 0 ? `${a} ${b}` : `${a}${b}`
})
console.log(result)
//zxx: 这个正则可以的,支持小数
var numberCode = "5702375",
reg = /\B(?=(\d{3})+(?!\d))/g
console.log(numberCode.replace(reg, ','))
// zxx: 最好取几位小数
var size = 2837475
function foo(size){
var K = 1024,
M = K * 1024,
G = M * 1024,
_K = size/K,
_M = size/M,
_G = size/G
if(_G>1) return `${_G}G`
if(_M>1) return `${_M}M`
return `${_K}K`
}
console.log(foo(size))
张大大这是暗示往 6222 0818 1200 2934 027 里打 5,702,375 吗?
// zxx: 代码高亮有问题,题1题2均有问题
function formatStr(soure,format,insertStr,loopFormat=false,forward=true,needEnd=false,protect=1000) {
var resultStr = '';
if(forward){
for(var i=0,j=0;i<format.length && j<soure.length;protect--){
if(protect<0){
console.log('over limit times');
console.log('limit times: ',protect);
break;
}
resultStr+=soure.slice(j,j+format[i])+insertStr;
j+=format[i];
i++;
if(loopFormat && i>=format.length){
i=0
}
}
if(!needEnd){
resultStr = resultStr.substring(0,resultStr.length-insertStr.length)
}
}
else{
for(var i=0,j=soure.length;i<format.length && j>0;protect--){
if(protect<0){
console.log('over limit times');
console.log('limit times: ',protect);
break;
}
var start = j-format[i];
if(start<0){
start = 0;
}
resultStr=insertStr+soure.slice(start,j)+resultStr;
j=start;
i++;
if(loopFormat && i>=format.length){
i=0
}
}
if(!needEnd){
resultStr = resultStr.substring(insertStr.length)
}
}
return resultStr
}
第一题:
var bankCode = '6222081812002934027';
formatStr(bankCode,[4,4,4,4,3],' ')
第二题:
var numberCode = '5702375';
formatStr(numberCode,[3],',',true,false);
第三题:
var fileSize = 2837475;
function showFileSize(fileSize) {
var K = 1024,M = 1048576,G = 1073741824;
if(fileSize > G){
return (fileSize/G).toFixed(3)+'G';
}
else if(fileSize > M){
return (fileSize/M).toFixed(3)+'M';
}
else if(fileSize > K){
return (fileSize/K).toFixed(3)+'K';
}
else {
return fileSize+'B';
}
}
showFileSize(fileSize);
https://www.zhangxinxu.com/wordpress/2017/09/web-page-comma-number/
//第一题
var bankCode = '6222081812002934027';
bankCode.replace(/\S{4}/g,v=>v+' ');
//"6222 0818 1200 2934 027" bankCode = '6222081812002934027';
//"6222 0818 1200 293X XXX" bankCode = '622208181200293XXXX';
//第二题
var numberCode = '5702375';
(+numberCode).toLocaleString('en-US',{useGrouping:true});
//"5,702,375" numberCode = '5702375';
//"845" numberCode = '845';
//"34,384.523" numberCode = '34384.5234';
//了解更多js国际化 https://segmentfault.com/a/1190000018685063
//第三题
// zxx: filesize是字节大小哟~
var filesize = 2837475;
(filesize>>20?filesize/2**20+'G'
:filesize>>10?filesize/2**10+'M'
:filesize+'K')
.replace(/(?<=\.)\d+/,v=>Math.round(v/10**(`${v}`.length-2)))
//"2.71G" filesize = 2837475;
//"2.77M" filesize = 2837;
//"283K" filesize = 283;
//补一个函数式的
Array.from({length:3},v=>filesize)
.map((v,i)=>[(v/2**(i*10)).toFixed(2),'KMG'[i]])
.find((v,i)=>v[0]<1024||i==2).join('')
//"2.71G" filesize = 2837475;
1. bankCode.replace(/(\d{4})/g, '$1 ')
2. Number(numberCode).toLocaleString()
3.
function formatFileSize(fileSize) {
const K = 1024;
const M = K * 1024;
const G = M * 1024
if (fileSize < M) {
return (fileSize / K).toFixed(2) + 'K'
} else if (fileSize > M) {
return (fileSize / M).toFixed(2) + 'M'
} else if (fileSize > G) {
return (fileSize / G).toFixed(2) + 'G'
}
}
var newSize = formatFileSize(filesize);
// 第 1 题
var bankCode = '6222081812002934027';
console.log(bankCode.trim().replace(/(\d{4})(?=\d)/g, "$1 "));
// 第 2 题
var numberCode = '5702375';
console.log(Number(numberCode).toLocaleString()) // 两种都可
console.log(Number(numberCode).toLocaleString('en-US'))
// 第 3 题
var filesize = 2837475;
var res = formatSize(filesize)
function formatSize (size = Number(size)) {
if (isNaN(size)) {
return '请使用合法数值'
}
const unit = 1024
var res = ''
switch (true) {
case size < Math.pow(unit, 2):
res = (size / unit).toFixed(2) + "K"
break
case size < Math.pow(unit, 3):
res = (size / Math.pow(unit, 2)).toFixed(2) + "M";
break
case size < Math.pow(unit, 4):
res = (size / Math.pow(unit, 3)).toFixed(2) + "G";
}
return res
}
1.
bankCode.replace(/(\d{4})(?=(\d)+$)/g,'$1 ');
2.
Number(numberCode).toLocaleString()
numberCode.replace(/(\d)(?=(\d{3})+$)/g,'$1,');
3.
function filesSizeFormat(size) {
let k = size / 1024,
m = k / 1024,
g = m / 1024;
return g >= 1 ? g + 'G' : m >= 1 ? m + 'M' : k + 'K';
}
let bankCode = '6222081812002934027';
bankCode = bankCode.replace(/(\d{4})/g, "$1 ");
console.log(bankCode);
let numberCode = '5702375';
numberCode = numberCode.replace(/(?!^)(?=(\d{3})+$)/g, ",")
console.log(numberCode);
let filesize = 2837475;
const getSize = (size) => {
let k = (size / 1024).toFixed(2);
let m = (size / 1024).toFixed(2);
let g = (m / 1024).toFixed(2);
return g >= 1 ? g + "G" : m >= 1 ? m + "M" : k + "K";
};
console.log(getSize(filesize));
function replaceRule(reg){
return function(str, replaceContent){
console.log(str.replace(reg, replaceContent));
return str.replace(reg, replaceContent);
}
};
console.log("------------------------测试用例银行卡号---------------------------------")
let bankRule = replaceRule(/(\d{4})/g);
bankRule("6222081812002934027", "$1 ")
bankRule("1".repeat(19), "$1 ")
bankRule("2".repeat(19), "$1 ")
console.log("------------------------测试用例钱---------------------------------")
let moneyRule = replaceRule(/(?!^)(?=(\d{3})+$)/g);
moneyRule("5702375", ",")
moneyRule("10", ",")
moneyRule("2000", ",")
moneyRule("123456789", ",")
moneyRule("11111111111111111111111111111111", ",")
console.log("------------------------测试用例文件大小---------------------------------")
console.log(getSize(2837475));
console.log(getSize(2090));
console.log(getSize(1024 ** 2 + 6666));
console.log(getSize(5201314));
<div>
<input type="number" id="cardinput"><button id="card">卡号</button><span class="cardtxt"></span>
</div>
<div>
<input type="number" id="moneyinput"><button id="money">人民币</button><span class="moneytxt"></span>
</div>
<div>
<input type="number" id="fileinput"><button id="file">文件大小</button><span class="filetxt"></span>
</div>
// 第一题
// zxx: 和题意不符
function bankformat(card) {
return card.replace(/(.{1})/g, "$1 ")
}
// 第二题
function format(num) {
var reg = /\d{1,3}(?=(\d{3})+$)/g;
return (num + '').replace(reg, '$&,');
}
// 第三题
function getfilesize(size) {
if (!size)
return "";
var num = 1024.00; //byteCCC
if (size > Math.pow(num, 3)) {
return (size / Math.pow(num, 3)).toFixed(2) + "G"; //G
} else if (size > Math.pow(num, 2)) {
return (size / Math.pow(num, 2)).toFixed(2) + "M"; //M
} else {
return (size / num).toFixed(2) + "K"; //kb
}
}
// 测试
let card = document.querySelector("#card")
let money = document.querySelector("#money")
let file = document.querySelector("#file")
let cardtxt = document.querySelector(".cardtxt")
let moneytxt = document.querySelector(".moneytxt")
let filetxt = document.querySelector(".filetxt")
card.addEventListener("click", function() {
let val = document.querySelector("#cardinput").value
cardtxt.innerHTML = bankformat(val)
})
money.addEventListener("click", function() {
let val = document.querySelector("#moneyinput").value
moneytxt.innerHTML = format(val)
})
file.addEventListener("click", function() {
let val = document.querySelector("#fileinput").value
filetxt.innerHTML = getfilesize(val)
})
测试 第一题
var bankCode = '1234123412341234123'
function one(bankCode) {
var oneReg = /(\d{4})/g
var newOneStr = bankCode.replace(oneReg, function (word) {
word = word + ' '
return word
})
console.log('第一题答案:', newOneStr)
}
one(bankCode) // 第一题答案: 1234 1234 1234 1234 123
第二题 方法一
var numberCode = 5702375.222
function two1(numberCode) {
var newTwoStr = parseFloat(numberCode).toLocaleString()
console.log('第二题的答案:', newTwoStr) // 5,702,375.222
}
two1(numberCode) // 第二题的答案: 5,702,375.222
方法二
var numberCode = 5702375.222
function two2(num) {
var numberCode = num.toString()
var twoReg1 = /^\d+/g
var twoReg2 = /(?=(\B)(\d{3})+$)/g
var newTwoStr = numberCode.replace(twoReg1, function (word) {
// console.log(word)
word = word.replace(twoReg2, function (word2) {
// console.log(word2)
word2 = ',' + word2
return word2
})
// console.log(word)
return word
})
console.log('第二题的答案:', newTwoStr) // 第二题的答案: 5,702,375.222
}
two2(numberCode)
第三问
var filesize = 2837475
function three(filesize) {
if (parseInt(filesize) < 1024 || parseInt(filesize) === 1024) {
console.log('第三题的答案:', filesize.toFixed(3) + 'K')
}
if (parseInt(filesize) > 1024 && parseInt(filesize) < 1024 * 1024) {
console.log('第三题的答案:', (filesize / 1024).toFixed(3) + 'M')
}
if (parseInt(filesize) > 1024 * 1024 || parseInt(filesize) === 1024 * 1024) {
console.log('第三题的答案:', (filesize / (1024 * 1024)).toFixed(3) + 'G')
}
}
three(filesize) // 第三题的答案: 2.706G
// 第一题
let test1 = '6222081812002934027'.replace(/(\d{4})(?=(\d))/g, '$1 ')
console.log(test1)
// 保证最后一位始终不会出现空格
let test2 = '62220818120029340270'.replace(/(\d{4})(?=(\d))/g, '$1 ')
console.log(test2)
// 第二题
let test3 = '5702375'.replace(/(?!^)(?=(\d{3})+$)/g, ',')
console.log(test3)
// 保证第一位始终不会出现分隔符
let test4 = '570237'.replace(/(?!^)(?=(\d{3})+$)/g, ',')
console.log(test4)
// 第三题
function formatSize(size) {
size = parseFloat(size) / 1024
let unitArr = ['K', 'M', 'G']
let _index = 0
while(size / 1024 >= 1 && _index < unitArr.length - 1) {
size = size / 1024
++_index
}
return `${size}${unitArr[_index]}`
}
console.log(formatSize(2837475))
console.log(formatSize(12))
console.log(formatSize(1024))
console.log(formatSize(1024*1000))
console.log(formatSize(1024*1024))
console.log(formatSize(1024*1024*1000))
console.log(formatSize(1024*1024*1024))
console.log(formatSize(1024*1024*1024*1000))
console.log(formatSize(1024*1024*1024*1024))
// 1
var bankCode = '6222081812002934027'
// 方法一
var transBankCode = function(code) {
var len = parseInt(code.length / 4)
var str = ''
for (var i = 1; i <= len; i++) {
str += `${code.slice(4 * (i - 1), 4 * i)} `
}
str += code.slice(4 * len, 4 * (len + 1))
return str
}
console.log(transBankCode(bankCode))
// 方法二 使用正则表达式
console.log(bankCode.replace(/\S{4}/g, i => i + ' '))
// 2
var numberCode = '5702375'
// 方法一
var transNumberCode = function(code) {
var len = parseInt(code.length / 3)
var str = ''
for (var i = 1; i <= len; i++) {
var a = -3 * i
var b = -3 * (i - 1)
if (b === 0) {
str = `,${code.slice(a)}` + str
} else {
str = `,${code.slice(a, b)}` + str
}
}
str = code.slice(0, -(3 * len)) + str
return str
}
console.log(transNumberCode(numberCode))
// 方法二 正则表达式
console.log(numberCode.replace(/(?<=\d)(?=(\d{3})+\b)/g, i => ',' + i))
// 方法三
console.log(Number(numberCode).toLocaleString())
// 3
// 转换文件大小
var filesize = 2837475
// n 是传入文件的大小 p是保留几位小数(默认取两位小数)
var transFileSize = function(n, p = 2) {
function round(number, precision) {
return Math.round(+number + 'e' + precision) / 10 ** precision;
}
n = Number(n)
if (isNaN(n)) {
return 0
}
if (n < 1024 ** 2) {
return `${round(n / 1024, p)}K`
} else if (n >= 1024 ** 2 && n < 1024 ** 3) {
return `${round(n / (1024 ** 2), p)}M`
} else {
return `${round(n / (1024 ** 3), p)}G`
}
}
console.log(transFileSize(filesize))
题目1
function splitBankCode (code) { return code.replace(/(\d{4})/g, '$1 ').trim() } //19位银行卡号 console.log(splitBankCode('6222081812002934027')) //16位银行卡号 console.log(splitBankCode('6222081812002934'))
题目2
function splitNumber (num) { num = String(num); if (num.length>3) { return splitNumber(num.substr(0, num.length - 3)) + ',' + num.substr(-3) } else return num } console.log(splitNumber(12345)); console.log(splitNumber(123456)); console.log(splitNumber(1234567));
题目3
function format (size) { let K = 1024; let M = 1024 * K; let G = 1024 * M; let units = [{ size: G, name: 'G' }, { size: M, name: 'M' }, { size: K, name: 'K' }] for (let i=0; i<units.length; i++) { if (units[i].size<=size || size<K) { return (size / units[i].size).toFixed(2) + units[i].name } } } console.log(format(2837475)); console.log(format(676552834)); // zxx:你这个为什么返回undefined // 之前判断写反了... console.log(format(98765432111));
demo 1.
var bankCode = '6222081812002934027';
var bankReg = /(?!^)(?=(\d{4})+\d{3}$)|(?=\d{3}$)/g
bankCode = bankCode.replace(bankReg, function () {
return ' '
})
2.
var numberCode = '5702375';
var numReg = /(?=(\d{3})+$)/g
numberCode = numberCode.replace(numReg, function () {
return ','
})
3.
var filesize = 2837475;
function format(size) {
var newSize;
var kSize = 1024;
var mSize = 1024 * 1024;
var gSize = 1024 * 1024 * 1024;
if(size >= gSize){
newSize = (size / gSize).toFixed(2) + 'G';
}else if(size >= mSize){
newSize = (size / mSize).toFixed(2) + 'M';
}else {
newSize = (size / kSize).toFixed(2) + 'K';
}
return newSize
}
1.
var bankCode = '6222081812002934027';
let i=0
let arr = []
while(i<bankCode.length) {
arr.push(bankCode[i])
i++
if (i%4===0) {
arr.push(' ')
}
}
console.log(arr.join(''))
2.
var numberCode = '5702375';
var start = numberCode.length%3
var startStr = numberCode.slice(0,start)+','
let j = start
while(j<numberCode.length) {
startStr+=numberCode[j]
j++
if((j-start)%3===0){
startStr+=','
}
}
let retStr = startStr.slice(0,-1)
console.log(retStr)
3.
var filesize = 2837475;
var sizes = ['K', 'M', 'G'];
var i = parseInt(Math.floor(Math.log(filesize) / Math.log(1024)));
i = i>3?3:i
// 保留两位小数
var ret =Math.round(filesize*100 / Math.pow(1024, i))/100 + sizes[i-1];
console.log(ret)
1.
var bankCode = '6222081812002934027';
console.log(bankCode.replace(/(\d{4})/g, '$1 '));
2.
// zxx: 不错,支持小数
var numberCode = '995702375';
console.log(numberCode.replace(/\B(?=(\d{3})+\b)/g, ','));
3.
function formatFileSize (filesize = 1023) {
let K = 1024,
M = 1024 ** 2,
G = 1024 ** 3;
switch(true) {
case filesize > G:
return (filesize / G).toFixed(1) + "G";
case filesize > M:
return (filesize / M).toFixed(1) + "M";
case filesize > K:
return (filesize / K).toFixed(1) + "K";
default:
return filesize + "B";
}
}
console.log(formatFileSize());
console.log(formatFileSize(1025));
console.log(formatFileSize(1024 ** 2 + 1));
console.log(formatFileSize(1024 ** 3 + 1));
var backCode = '6222081812002934027';
// 方法1
var result = backCode.replace(/(\d{4})/g, '$1 ');
console.log(result); // "6222 0818 1200 2934 027"
// 方法2
var result = backCode.split(/(\d{4})/).filter(s => !!s).join(' ');
console.log(result); // "6222 0818 1200 2934 027"
var numberCode = ‘5702375’;
var result = numberCode.replace(/\d{1,3}(?=(\d{3})+$)/g, '$&,'); // 未考虑小数情况
console.log(result); // "5,702,375"
var filesize = 2837475;
function matchUnit(value) {
var sizeUnits = ['K', 'M', 'G'];
var sizeRadix = 1024;
if (value < sizeRadix) {
return (value / sizeRadix).toFixed(1) + sizeUnits[0]
}
for (var i = sizeUnits.length - 1; i >= 0; i--) {
var radix = Math.pow(sizeRadix, i + 1);
if (value >= radix) {
return (value / radix).toFixed(1) + sizeUnits[i]
}
}
}
console.log(matchUnit(filesize)); // 2.7M
console.log(matchUnit(100)); // 0.1K
console.log(matchUnit(10000)); // 9.8K
console.log(matchUnit(100000000)); // 95.4M
console.log(matchUnit(10000000000)); // 9.3G
//1
var bankCode = '6222081812002934027';
bankCode.replace(/(\d{4})/g,'$1 ');
//2
var numberCode = '5702375';
Number(numberCode).toLocaleString('en-US');
//3
var filesize = 2837475;
function format(size){
return size>1024**3&&(size/1024**3).toFixed(2)+'G' ||
size>1024**2&&(size/1024**2).toFixed(2)+'M' ||
(size/1024).toFixed(2)+'K';
}
format(2837475555) //2.64G
format(2837475) //2.71M
format(28374) //27.71K
第一题
var bankCode = '6222081812002934027'
var formatterCode = bankCode.replace(/(\d{4})(?!$)/g, '$1')
console.log(formatterCode)
第二题
var numberCode = 5702375
var formatterNumberCode = numberCode.toLocaleString()
console.log(formatterNumberCode)
// or
numberCode = 1024.1235888
var formatterNumberCode = String(numberCode).replace(/(?<!\.\d*)\B(?=(\d{3})+(?!\d))/g, ',')
console.log(formatterNumberCode)
第三题
//3.
var filesize = 2837475;
function formatterFilesize(filesize) {
if (filesize < 1024 ** 2) {
return filesize / 1024 + 'KB'
} else if (1024 ** 2 <= filesize && filesize < 1024 ** 3) {
return filesize / (1024 ** 2) + 'MB'
} else {
return filesize / (1024 ** 3) + 'GB'
}
}
console.log(formatterFilesize(filesize))
console.log(formatterFilesize(1024))
console.log(formatterFilesize(1024 ** 2))
console.log(formatterFilesize(1024 ** 3))
// 1
var bankCode = '6222081812002934027';
var firstResult = bankCode.replace(/(\d{4})/g, '$1 ');
console.log(firstResult);
// 2
var numberCode = '5702375';
var secondResult = (+numberCode).toLocaleString('en-US');
console.log(secondResult);
var secondAnthor = numberCode.replace(/\B(?=(\d{3})+$)/g, ',');
console.log(secondAnthor)
// 3
var UNITS = ['K', 'M', 'G'];
function bytesToSize(number) {
if (!Number.isFinite(number)) {
throw new Error('需求有限数值, 却得到 ' + typeof number + ':' + number);
}
number = number / 1000;
var isNegative = number < 0;
var prefix = isNegative ? '-' : '';
if (isNegative) {
number = -number;
}
if (number < 1) {
return prefix + number + ' ' + UNITS[0];
}
var exponent = Math.min(
Math.floor(Math.log10(number) / 3),
UNITS.length - 1
);
number = (number / Math.pow(1000, exponent)).toPrecision(3);
return prefix + number + ' ' + UNITS[exponent];
}
var filesize = -2837475;
var thirdResult = bytesToSize(filesize);
console.log(thirdResult);
第一题
var bankCode = "6222081812002934027";
bankCode = bankCode.replace(/(\d{4})(?=\d)/g, "$1 ");
console.log(bankCode);
第二题
var numberCode = '5702375';
numberCode = parseInt(numberCode).toLocaleString();
console.log(numberCode);
第三题
var fileSize = 2837475;
var K = 1024;
var M = 1024 * 1024;
var G = 1024 * 1024 * 1024;
var size = "";
if(fileSize >= G){
size = (fileSize / G).toFixed(2) + "G";
}else if(fileSize >= M){
size = (fileSize / M).toFixed(2) + "M";
}else{
size = (fileSize / K).toFixed(2) + "K";
}
console.log(size);
// 第一题
//zxx: mark,有意思的实现
let bankCode = '6222081812002934027';
let bankCodeArr = bankCode.match(/\d{3,4}/g);
document.write(bankCodeArr.join(' '));
document.write('<br/>');
// 第二题
let numberCode = '5702375';
let numberCodeReverse = numberCode.split('').reverse().join('');
let numberCodeArr = numberCodeReverse.match(/\d{1,3}/g);
document.write(numberCodeArr.reverse().join(','));
document.write('<br/>');
// 第三题 K,M,G
let fileSize = 2837475;
let K = 1024;
let size = '';
if (fileSize >= K ** 3) {
size = (fileSize / K ** 3).toFixed(2) + "G";
} else if (fileSize >= K ** 2) {
size = (fileSize / K ** 2).toFixed(2) + "M";
} else {
size = (fileSize / K).toFixed(2) + "K";
}
document.write(size);
function formatNumber(num) {
var result = '';
while (num.length > 3) {
result = ',' + num.slice(-3) + result;
num = num.slice(0, num.length - 3);
}
if (num) {
result = num + result;
}
return result;
}
function formatFileSize(size) {
var K = 1024, M = K * K, G = M * K;
if (size > G) {
return (size / G).toFixed(2) + 'G';
} else if (size > M) {
return (size / M).toFixed(2) + 'M';
} else {
return size + 'K';
}
}
//第一题
"621483018499184".replace(/(\d{4})(?=\d)/g, "$1 ");
//第二题
parseInt("5702375").toLocaleString();
console.log(parseInt("5702375").toLocaleString());
//Intl.NumberFormat是对语言敏感的格式化数字类的构造器类
//具体语法参考https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
console.log(new Intl.NumberFormat().format(parseInt("5702375")));
console.log(formatNumber("5702375"));
//第三题
console.log(formatFileSize(2837475));
console.log(formatFileSize(234));
console.log(formatFileSize(5367367369));
// 1
var bankCode = '6222081812002934027';
var formatCode = `${bankCode.slice(0,4)} ${bankCode.slice(4,8)} ${bankCode.slice(8,12)} ${bankCode.slice(12,16)} ${bankCode.slice(16)}`;
// 2
// 简单的
var numberCode = '5702375';
var formatNumber = Number.prototype.toLocaleString.apply(parseInt(numberCode, 10));
// 从数字后面循环
var numberCode = '5702375';
var formatNumber1 = '';
while(numberCode.length>3){
formatNumber1 = ','+numberCode.slice(-3)+formatNumber1;
numberCode = numberCode.slice(0, -3);
}
if (numberCode) formatNumber1 = numberCode+formatNumber1;
// 使用正则,从后面向前匹配
var numberCode = '5702375';
var formatNumber2 = numberCode.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
// 3 1GB = 1024MB = 1024*1024KB = 1024*1024*1024B
var filesize = 2837475;
function transMemory(volume, current){
if(!current) current = '';
if (volume < 1024 * 1024) { // 如果容量小于1mb
return current + volume / 1024 + 'K';
} else if( volume < 1024 * 1024 * 1024 ) { // 如果容量小于 1GB
return transMemory(volume % (1024 * 1024), current+Math.floor(volume / (1024 * 1024))+'M');
} else { // 容量大于1GB
return transMemory(volume % (1024 * 1024 * 1024), current+Math.floor(volume / (1024 * 1024 * 1024))+'G');
}
}
var formatSize = transMemory(filesize);
// formatSize输出结果为:2M722.9716796875K
console.log(transMemory(123456789)); // 117M755.2705078125K
console.log(transMemory(74125896365)); // 69G35M986.6689453125K
// 容量在线转换工具结果在下面,有图片
1
var bankcode = '6222081812002934027'
let func1 = (code) => {
let length = code.length
if (length === 19) {
let arr = []
for (let i = 0; i < length; i += 4) {
arr.push(code.slice(i, i + 4))
}
let result = arr.join(' ')
return result
} else {
return 'not valid bankcode'
}
}
// test
console.log(func1(''))
console.log(func1(bankcode))
console.log(func1(bankcode + '1'))
2
var numbercode = '5702375'
let func2 = (code) => {
let length = code.length
let count = 0
let result = ''
for (let i = 0; i < length; i++) {
let n = code[length - 1 - i]
count += 1
if (count === 3) {
result = ',' + n + result
count = 0
} else {
result = n + result
}
}
return result
}
// test
console.log(func2(''))
console.log(func2(numbercode))
console.log(func2('0000000000000000000'))
3
var filesize = 2837475
let func3 = (bite) => {
let kb = bite / 1024
let mb = bite / (1024 * 1024)
let gb = bite / (1024 * 1024 * 1024)
if (mb <= 1) {
return kb + 'kb'
} else if (gb <= 1) {
return mb + 'mb'
} else {
return gb + 'gb'
}
}
// test
console.log(func3(0))
console.log(func3(1024))
console.log(func3(1025))
console.log(func3(1024 * 1024))
console.log(func3(1024 * 1024 + 1))
console.log(func3(1024 * 1024 * 1024))
console.log(func3(1024 * 1024 * 1024 + 1))
我的蠢方法
// https://github.com/zhangxinxu/quiz/issues/42
// 2019 - 9-6
// 1
var bankCode = '6222081812002934027';
var formlist = [4,4,4,4,3];
function getFormBankCode(bankCode,formlist){
var count = 0 ;
var cutCode = [];
for(var i = 0; i< formlist.length; i++ ){
cutCode.push(bankCode.slice(count , count + formlist[i]) )
count = count + formlist[i];
}
return cutCode.join(" ");
}
console.log(getFormBankCode(bankCode,formlist)) ;
// 2
var numberCode = '5702375';
console.log( (numberCode - 0 ).toLocaleString());
// 3
var filesize = 2837475;
function getSize(filesize){
if ( filesize / 1024 > 0 ){
filesize = filesize / 1024;
if( filesize / 1024 > 0) {
filesize = filesize / 1024;
return filesize + "G";
}
else{
return filesize + "M";
}
}else{
return filesize + "K";
}
}
console.log( getSize(filesize) );
正则是个好东西啊,总觉得好多高级用法还不清楚怎么用;
var bankCode = '6222081812002934027'
var numberCode = '5702375'
var fileSize = 2837475
// 1
function bankFormat (str) {
return str.replace(/(\d{4})/g, '$1 ')
}
// 2:正则没有逆向查找?
function moneyFormat (str) {
const reverseString = str => str.split('').reverse().join('')
return reverseString(reverseString(str).replace(/(\d{3})/g, '$1,'))
}
// 3:暂时没考虑小数点的取舍
function sizeFormat (num) {
let res = ''
const G = 1024**3
const M = 1024**2
const K = 1024
if (num >= G) {
res = num / G + 'G'
} else if (num >= M) {
res = num / M + 'M'
} else {
res = num / K + 'K'
}
return res
}
console.log(bankFormat(bankCode)) // 6222 0818 1200 2934 027
console.log(moneyFormat(numberCode)) // 5,702,375
console.log(sizeFormat(fileSize)) // 2.706027030944824M
本期要点:
不好意思,这边错过了答题时间。不得分,但还是补齐一下我的答案:
// 第一题=============
var backCode = '6222081812002934027';
var newCode = '';
for (var i = 0, len = backCode.length; i < len; i = i + 4) {
// 每四个分段
newCode += ' ' + backCode.substr(i, 4);
}
// 去掉第一个空格
newCode = newCode.substr(1);
console.log(newCode);
// 第二题=============
var numberCode = '5702375';
var newNumber = '';
// 倒叙循环
for (var i = numberCode.length; i - 3 > 0; i = i - 3) {
newNumber = ',' + numberCode.substr(i - 3, 3) + newNumber;
}
// 填充第一组
newNumber = numberCode.substr(0, i) + newNumber;
console.log(newNumber);
// 第三题=============
var filesize = 2837475;
var K = 1024;
var M = 1024 * 1024;
var G = 1024 * 1024 * 1024;
var fileString = '';
if (filesize > G - 1) {
fileString = parseFloat(filesize / G).toFixed(2) + 'G';
} else if (filesize > M - 1) {
fileString = parseFloat(filesize / M).toFixed(2) + 'M';
} else {
fileString = parseFloat(filesize / K).toFixed(2) + 'K';
}
console.log(fileString);
本期小测关于字符格式处理:
答题前不要看别人回答,答题后可以,但不能修改自己回答
大家提交回答的时候,注意缩进距离,起始位置从左边缘开始;另外,github自带代码高亮,所以请使用下面示意的格式。
其它: