使用js实现数据格式化
格式化是通过格式操作使任意类型的数据转换成一个字符串。例如下面这样
<script>
console.log(chopper.format('{0}-{1}-{2}',12,24,25));//outputs"12-24-25"
</script>
下面是一个完整的代码,可以复制到自己的项目中。
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
</head>
<body>
<scriptsrc="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
(function(){
varchopper=window.chopper=window.chopper||{cultures:{}},
math=Math,
formatRegExp=/\{(\d+)(:[^\}]+)?\}/g,
FUNCTION="function",
STRING="string",
NUMBER="number",
OBJECT="object",
NULL="null",
BOOLEAN="boolean",
UNDEFINED="undefined",
slice=[].slice,
globalize=window.Globalize,
standardFormatRegExp= /^(n|c|p|e)(\d*)$/i,
literalRegExp=/(\\.)|(['][^']*[']?)|(["][^"]*["]?)/g,
commaRegExp=/\,/g,
EMPTY="",
POINT=".",
COMMA=",",
SHARP="#",
ZERO="0",
PLACEHOLDER="??",
EN="en-US",
objectToString={}.toString;
//cultures
chopper.cultures["en-US"]={
name:EN,
numberFormat:{
pattern:["-n"],
decimals:2,
",":",",
".":".",
groupSize:[3],
percent:{
pattern:["-n%","n%"],
decimals:2,
",":",",
".":".",
groupSize:[3],
symbol:"%"
},
currency:{
pattern:["($n)","$n"],
decimals:2,
",":",",
".":".",
groupSize:[3],
symbol:"$"
}
},
calendars:{
standard:{
days:{
names:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
namesAbbr:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],
namesShort:["Su","Mo","Tu","We","Th","Fr","Sa"]
},
months:{
names:["January","February","March","April","May","June","July","August","September","October","November","December"],
namesAbbr:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
},
AM:["AM","am","AM"],
PM:["PM","pm","PM"],
patterns:{
d:"M/d/yyyy",
D:"dddd,MMMMdd,yyyy",
F:"dddd,MMMMdd,yyyyh:mm:sstt",
g:"M/d/yyyyh:mmtt",
G:"M/d/yyyyh:mm:sstt",
m:"MMMMdd",
M:"MMMMdd",
s:"yyyy'-'MM'-'ddTHH':'mm':'ss",
t:"h:mmtt",
T:"h:mm:sstt",
u:"yyyy'-'MM'-'ddHH':'mm':'ss'Z'",
y:"MMMM,yyyy",
Y:"MMMM,yyyy"
},
"/":"/",
":":":",
firstDay:0,
twoDigitYearMax:2029
}
}
};
functionfindCulture(culture){
if(culture){
if(culture.numberFormat){
returnculture;
}
if(typeofculture===STRING){
varcultures=chopper.cultures;
returncultures[culture]||cultures[culture.split("-")[0]]||null;
}
returnnull;
}
returnnull;
}
functiongetCulture(culture){
if(culture){
culture=findCulture(culture);
}
returnculture||chopper.cultures.current;
}
functionexpandNumberFormat(numberFormat){
numberFormat.groupSizes=numberFormat.groupSize;
numberFormat.percent.groupSizes=numberFormat.percent.groupSize;
numberFormat.currency.groupSizes=numberFormat.currency.groupSize;
}
chopper.culture=function(cultureName){
varcultures=chopper.cultures,culture;
if(cultureName!==undefined){
culture=findCulture(cultureName)||cultures[EN];
culture.calendar=culture.calendars.standard;
cultures.current=culture;
if(globalize&&!globalize.load){
expandNumberFormat(culture.numberFormat);
}
}else{
returncultures.current;
}
};
chopper.culture(EN);
//numberformatting
functionformatNumber(number,format,culture){
culture=getCulture(culture);
varnumberFormat=culture.numberFormat,
groupSize=numberFormat.groupSize[0],
groupSeparator=numberFormat[COMMA],
decimal=numberFormat[POINT],
precision=numberFormat.decimals,
pattern=numberFormat.pattern[0],
literals=[],
symbol,
isCurrency,isPercent,
customPrecision,
formatAndPrecision,
negative=number<0,
integer,
fraction,
integerLength,
fractionLength,
replacement=EMPTY,
value=EMPTY,
idx,
length,
ch,
hasGroup,
hasNegativeFormat,
decimalIndex,
sharpIndex,
zeroIndex,
hasZero,hasSharp,
percentIndex,
currencyIndex,
startZeroIndex,
start=-1,
end;
//returnemptystringifnonumber
if(number===undefined){
returnEMPTY;
}
if(!isFinite(number)){
returnnumber;
}
//ifnoformatthenreturnnumber.toString()ornumber.toLocaleString()ifculture.nameisnotdefined
if(!format){
returnculture.name.length?number.toLocaleString():number.toString();
}
formatAndPrecision=standardFormatRegExp.exec(format);
//standardformatting
if(formatAndPrecision){
format=formatAndPrecision[1].toLowerCase();
isCurrency=format==="c";
isPercent=format==="p";
if(isCurrency||isPercent){
//getspecificnumberformatinformationifformatiscurrencyorpercent
numberFormat=isCurrency?numberFormat.currency:numberFormat.percent;
groupSize=numberFormat.groupSize[0];
groupSeparator=numberFormat[COMMA];
decimal=numberFormat[POINT];
precision=numberFormat.decimals;
symbol=numberFormat.symbol;
pattern=numberFormat.pattern[negative?0:1];
}
customPrecision=formatAndPrecision[2];
if(customPrecision){
precision=+customPrecision;
}
//returnnumberinexponentialformat
if(format==="e"){
returncustomPrecision?number.toExponential(precision):number.toExponential();//toExponential()andtoExponential(undefined)differinFF#653438.
}
//multiplyifformatispercent
if(isPercent){
number*=100;
}
number=round(number,precision);
negative=number<0;
number=number.split(POINT);
integer=number[0];
fraction=number[1];
//exclude"-"ifnumberisnegative.
if(negative){
integer=integer.substring(1);
}
value=integer;
integerLength=integer.length;
//addgroupseparatortothenumberifitislongerenough
if(integerLength>=groupSize){
value=EMPTY;
for(idx=0;idx<integerLength;idx++){
if(idx>0&&(integerLength-idx)%groupSize===0){
value+=groupSeparator;
}
value+=integer.charAt(idx);
}
}
if(fraction){
value+=decimal+fraction;
}
if(format==="n"&&!negative){
returnvalue;
}
number=EMPTY;
for(idx=0,length=pattern.length;idx<length;idx++){
ch=pattern.charAt(idx);
if(ch==="n"){
number+=value;
}elseif(ch==="$"||ch==="%"){
number+=symbol;
}else{
number+=ch;
}
}
returnnumber;
}
//customformatting
//
//separateformatbysections.
//makenumberpositive
if(negative){
number=-number;
}
if(format.indexOf("'")>-1||format.indexOf("\"")>-1||format.indexOf("\\")>-1){
format=format.replace(literalRegExp,function(match){
varquoteChar=match.charAt(0).replace("\\",""),
literal=match.slice(1).replace(quoteChar,"");
literals.push(literal);
returnPLACEHOLDER;
});
}
format=format.split(";");
if(negative&&format[1]){
//getnegativeformat
format=format[1];
hasNegativeFormat=true;
}elseif(number===0){
//formatforzeros
format=format[2]||format[0];
if(format.indexOf(SHARP)==-1&&format.indexOf(ZERO)==-1){
//returnformatifitisstringconstant.
returnformat;
}
}else{
format=format[0];
}
percentIndex=format.indexOf("%");
currencyIndex=format.indexOf("$");
isPercent=percentIndex!=-1;
isCurrency=currencyIndex!=-1;
//multiplynumberiftheformathaspercent
if(isPercent){
number*=100;
}
if(isCurrency&&format[currencyIndex-1]==="\\"){
format=format.split("\\").join("");
isCurrency=false;
}
if(isCurrency||isPercent){
//getspecificnumberformatinformationifformatiscurrencyorpercent
numberFormat=isCurrency?numberFormat.currency:numberFormat.percent;
groupSize=numberFormat.groupSize[0];
groupSeparator=numberFormat[COMMA];
decimal=numberFormat[POINT];
precision=numberFormat.decimals;
symbol=numberFormat.symbol;
}
hasGroup=format.indexOf(COMMA)>-1;
if(hasGroup){
format=format.replace(commaRegExp,EMPTY);
}
decimalIndex=format.indexOf(POINT);
length=format.length;
if(decimalIndex!=-1){
fraction=number.toString().split("e");
if(fraction[1]){
fraction=round(number,Math.abs(fraction[1]));
}else{
fraction=fraction[0];
}
fraction=fraction.split(POINT)[1]||EMPTY;
zeroIndex=format.lastIndexOf(ZERO)-decimalIndex;
sharpIndex=format.lastIndexOf(SHARP)-decimalIndex;
hasZero=zeroIndex>-1;
hasSharp=sharpIndex>-1;
idx=fraction.length;
if(!hasZero&&!hasSharp){
format=format.substring(0,decimalIndex)+format.substring(decimalIndex+1);
length=format.length;
decimalIndex=-1;
idx=0;
}if(hasZero&&zeroIndex>sharpIndex){
idx=zeroIndex;
}elseif(sharpIndex>zeroIndex){
if(hasSharp&&idx>sharpIndex){
idx=sharpIndex;
}elseif(hasZero&&idx<zeroIndex){
idx=zeroIndex;
}
}
if(idx>-1){
number=round(number,idx);
}
}else{
number=round(number);
}
sharpIndex=format.indexOf(SHARP);
startZeroIndex=zeroIndex=format.indexOf(ZERO);
//definetheindexofthefirstdigitplaceholder
if(sharpIndex==-1&&zeroIndex!=-1){
start=zeroIndex;
}elseif(sharpIndex!=-1&&zeroIndex==-1){
start=sharpIndex;
}else{
start=sharpIndex>zeroIndex?zeroIndex:sharpIndex;
}
sharpIndex=format.lastIndexOf(SHARP);
zeroIndex=format.lastIndexOf(ZERO);
//definetheindexofthelastdigitplaceholder
if(sharpIndex==-1&&zeroIndex!=-1){
end=zeroIndex;
}elseif(sharpIndex!=-1&&zeroIndex==-1){
end=sharpIndex;
}else{
end=sharpIndex>zeroIndex?sharpIndex:zeroIndex;
}
if(start==length){
end=start;
}
if(start!=-1){
value=number.toString().split(POINT);
integer=value[0];
fraction=value[1]||EMPTY;
integerLength=integer.length;
fractionLength=fraction.length;
if(negative&&(number*-1)>=0){
negative=false;
}
//addgroupseparatortothenumberifitislongerenough
if(hasGroup){
if(integerLength===groupSize&&integerLength<decimalIndex-startZeroIndex){
integer=groupSeparator+integer;
}elseif(integerLength>groupSize){
value=EMPTY;
for(idx=0;idx<integerLength;idx++){
if(idx>0&&(integerLength-idx)%groupSize===0){
value+=groupSeparator;
}
value+=integer.charAt(idx);
}
integer=value;
}
}
number=format.substring(0,start);
if(negative&&!hasNegativeFormat){
number+="-";
}
for(idx=start;idx<length;idx++){
ch=format.charAt(idx);
if(decimalIndex==-1){
if(end-idx<integerLength){
number+=integer;
break;
}
}else{
if(zeroIndex!=-1&&zeroIndex<idx){
replacement=EMPTY;
}
if((decimalIndex-idx)<=integerLength&&decimalIndex-idx>-1){
number+=integer;
idx=decimalIndex;
}
if(decimalIndex===idx){
number+=(fraction?decimal:EMPTY)+fraction;
idx+=end-decimalIndex+1;
continue;
}
}
if(ch===ZERO){
number+=ch;
replacement=ch;
}elseif(ch===SHARP){
number+=replacement;
}
}
if(end>=start){
number+=format.substring(end+1);
}
//replacesymbolplaceholders
if(isCurrency||isPercent){
value=EMPTY;
for(idx=0,length=number.length;idx<length;idx++){
ch=number.charAt(idx);
value+=(ch==="$"||ch==="%")?symbol:ch;
}
number=value;
}
&nbs 热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短