형식은 형식 작업을 통해 모든 유형의 데이터를 문자열로 변환하는 것입니다. 예를 들어, 다음입니다
코드 사본은 다음과 같습니다.
<cript>
console.log (Chopper.format ( '{0} - {1} - {2}', 12, 24, 25)); // 출력 "12-24-25"
</스크립트>
다음은 자신의 프로젝트에 복사 할 수있는 완전한 코드입니다.
코드 사본은 다음과 같습니다.
<! doctype html>
<html>
<헤드>
<meta http-equiv = "content-type"content = "text/html; charset = utf-8">
</head>
<body>
<script src = "http://code.jquery.com/jquery-1.9.1.min.js"> </script>
<cript>
(기능() {
var chopper = window.chopper = window.chopper || {문화 : {}},
수학 = 수학,
formatregexp = // {(/d+) (: [^/}]+)?/}/g,
function = "function",
String = "String",
숫자 = "번호",
Object = "Object",
null = "null",
부울 = "부울",
undefined = "undefined",
슬라이스 = [] .Slice,
globmaze = window.globaliale,
Standardormatregexp =/^(n | c | p | e) (/d*) $/i,
literalRegexp = /(//.)|(라고 writege
commaregexp = //,/g,
empty = "" ",
point = ".",
comma = ",",
샤프 = "#",
Zero = "0",
자리 표시기 = "??",
en = "en-us",
ObjectToString = {} .ToString;
// 문화
Chopper.cultures [ "en-us"] = {
이름 : en,
Numberformat : {
패턴 : [ "-n"],
소수점 : 2,
",": ",",
".": ".",
그룹화 : [3],
퍼센트 : {
패턴 : [ "-n %", "n %"],
소수점 : 2,
",": ",",
".": ".",
그룹화 : [3],
기호 : "%"
},
통화 : {
패턴 : [ "($ n)", "$ n"],
소수점 : 2,
",": ",",
".": ".",
그룹화 : [3],
기호 : "$"
}
},
캘린더 : {
기준: {
날: {
이름 : [ "일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"],
NamesAbbr : [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
Namesshort : [ "SU", "MO", "TU", "We", "TH", "FR", "SA"]]]
},
달 : {
이름 : [ "1 월", "2 월", "3 월", "4 월", "5 월", 6 월 ","7 월 ","7 월 ","8 월 ","9 월 ","10 월 ","11 월 ","12 월 "],
NamesAbbr : [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "7 월", "8 월", "Sep", "Oct", "Nov", "Dec"]]]]
},
AM : [ "AM", "AM", "AM"],
PM : [ "PM", "PM", "PM"],
패턴 : {
D : "m/d/yyyy",
D : "DDDD, MMMM DD, YYYY",
F : "DDDD, MMMM DD, YYYY H : MM : SS TT",
G : "M/D/YYYY H : MM TT",
G : "m/d/yyyy h : mm : ss tt",
M : "mmmm dd",
M : "mmmm dd",
S : "yyyy '-'mm '-'ddthh ':'mm ':'ss",
T : "H : MM TT",
T : "H : MM : SS TT",
U : "yyyy '-'mm '-'dd hh ':'mm ':'ss'z '",
Y : "Mmmm, yyyy",
Y : "Mmmm, yyyy"
},
"/": "/",
":": ":",
첫날 : 0,
Twodigityearmax : 2029
}
}
};
기능 findculture (문화) {
if (문화) {
if (culture.numberformat) {
귀환 문화;
}
if (culture의 typeof === string) {
var 문화 = Chopper.cultures;
귀환 문화 [문화] || 문화 [Culture.split ( "-") [0] || 널;
}
널 리턴;
}
널 리턴;
}
기능 getculture (문화) {
if (문화) {
문화 = findculture (문화);
}
귀환 문화 || Chopper.cultures.current;
}
함수 expandnumberformat (numberformat) {
숫자 format.groupsize = numberformat.groupsize;
숫자 format.percent.groupsize = numberformat.percent.groupsize;
숫자 format.currency.groupsize = numberformat.currency.groupsize;
}
Chopper.culture = function (culturename) {
var 문화 = Chopper. 문화, 문화;
if (culturename! == 정의되지 않은) {
문화 = findculture (culturename) || 문화 [en];
문화 .calendar = Culture.Calendars.
문화 .current = 문화;
if (globaliMATED.LOAD) {
expandnumberformat (culture.numberformat);
}
} 또 다른 {
반환 문화. 통화;
}
};
Chopper.culture (en);
// 숫자 형식
함수 형식 내버 (번호, 형식, 문화) {
문화 = getculture (문화);
var numberformat = culture.numberformat,
groupsize = numberformat.groupsize [0],
groupseparator = numberformat [comma],
Decimal = numberformat [point],
정밀 = numberformat.decimals,
pattern = numberformat.pattern [0],
리터럴 = [],
상징,
iscurrency, aspercent,
CustomPrecision,
형식 프리즈,
음수 = 번호 <0,
정수,
분수,
정수 길이,
fractionlength,
교체 = 빈,
값 = 빈,
idx,
길이,
ch,
Hasproup,
hasnegativeformat,
DecimalIndex,
SharpIndex,
ZeroIndex,
Haszero, Hassharp,
퍼센트 덱스,
CurrencyIndex,
startzeroindex,
시작 = -1,
끝;
// 숫자가없는 경우 빈 문자열을 반환합니다
if (number === 정의되지 않은) {
비워 리 리턴;
}
if (! isfinite (number)) {
반품 번호;
}
// 형식이없는 경우 숫자를 반환합니다.
if (! 형식) {
Return Culture.name.length? 숫자.tolocalestring () : 숫자 .toString ();
}
FARMATANDPRECISION = StandardORMATREGEXP.Exec (형식);
// 표준 형식
if (formatandPrecision) {
format = FormatAndPrecision [1] .TOLOWERCASE ();
iscurrency = 형식 === "C";
ispercent = 형식 === "p";
if (iscurrency || ispercent) {
// 형식이 통화 또는 백분율 인 경우 특정 번호 형식 정보 가져옵니다.
숫자 format = iscurrency? 숫자 format.currency : numberformat.percent;
groupsize = numberformat.groupsize [0];
GroupSeparator = NumberFormat [comma];
Decimal = numberformat [point];
정밀도 = numberformat.decimals;
Symbol = numberformat.symbol;
pattern = numberformat.pattern [음수? 0 : 1];
}
CustomPrecision = FARMATANDPRECISION [2];
if (customprecision) {
정밀 = +CustomPrecision;
}
// 지수 형식의 반환 번호입니다
if (format === "e") {
CustomPrecision을 반환 하시겠습니까? 숫자. // ff #653438에서 다른 toexponential () 및 toexponential (정의되지 않은).
}
// 형식이 백분율인지 곱하십시오
if (ispercent) {
숫자 *= 100;
}
숫자 = 라운드 (번호, 정밀도);
음수 = 번호 <0;
숫자 = 숫자 .split (point);
정수 = 숫자 [0];
분수 = 숫자 [1];
// 제외 "-"숫자가 음수 인 경우 ".
if (음수) {
integer = integer.substring (1);
}
값 = 정수;
integerlength = integer.length;
// 충분히 길면 그룹 분리기를 숫자에 추가합니다.
if (integerlength> = groupsize) {
값 = 빈;
for (Idx = 0; idx <integerlength; idx ++) {
if (idx> 0 && (integerlength -idx) % groupsize === 0) {
값 += GroupSeparator;
}
값 += integer.charat (idx);
}
}
if (fraction) {
값 + = 소수 + 분수;
}
if (format === "n"&&! 음수) {
반환 값;
}
숫자 = 비어;
for (idx = 0, length = pattern.length; idx <length; idx ++) {
ch = pattern.charat (idx);
if (ch === "n") {
숫자 += 값;
} else if (ch === "$"|| ch === "%") {
번호 += 기호;
} 또 다른 {
숫자 += ch;
}
}
반품 번호;
}
// 사용자 정의 형식
//
// 섹션별로 형식을 구별합니다.
// 숫자를 긍정적으로 만듭니다
if (음수) {
숫자 = -덤프;
}
if (format.indexof ( " '")> -1 || format.indexof ( "/" ")> -1 || format.indexof ("// ")> -1) {
format = format.replace (literalRegexp, function (match) {
var quotechar = match.charat (0) .replace ( "//", ""),
literal = match.slice (1) .replace (quotchar, "");
리터럴 .push (문자);
자리 표시자를 반환합니다.
});
}
format = format.split ( ";");
if (negative && format [1]) {
// 음수 형식을 얻습니다
형식 = 형식 [1];
hasnegativeformat = true;
} else if (number === 0) {
// 0의 형식
형식 = 형식 [2] || 형식 [0];
if (format.indexof (sharp) == -1 && format.indexof (Zero) == -1) {
// 문자열이 상수 인 경우 형식을 반환합니다.
반환 형식;
}
} 또 다른 {
형식 = 형식 [0];
}
퍼센트 핀덱스 = Format.indexof ( "%");
CurrencyIndex = format.indexof ( "$");
ispercent = 퍼센트 덱스! = -1;
iscurrency = CurrencyIndex! = -1;
// 형식에 백분율이있는 경우 숫자를 곱하십시오
if (ispercent) {
숫자 *= 100;
}
if (iscurrency && format [CurrencyIndex -1] === "//") {
format = format.split ( "//"). join ( "");
iscurrency = false;
}
if (iscurrency || ispercent) {
// 형식이 통화 또는 백분율 인 경우 특정 번호 형식 정보 가져옵니다.
숫자 format = iscurrency? 숫자 format.currency : numberformat.percent;
groupsize = numberformat.groupsize [0];
GroupSeparator = NumberFormat [comma];
Decimal = numberformat [point];
정밀도 = numberformat.decimals;
Symbol = numberformat.symbol;
}
hasgroup = format.indexof (comma)> -1;
if (hasgroup) {
format = format.replace (commaregexp, empty);
}
DecimalIndex = format.indexof (point);
길이 = 형식 길이;
if (DecimalIndex! = -1) {
fraction = number.toString (). split ( "e");
if (fraction [1]) {
fraction = round (숫자, math.abs (fraction [1]);
} 또 다른 {
분수 = 분수 [0];
}
fraction = fraction.split (point) [1] || 비어 있는;
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);
길이 = 형식 길이;
DecimalIndex = -1;
idx = 0;
} if (haszero && Zeroindex> sharpindex) {
idx = Zeroindex;
} else if (sharpIndex> ZeroIndex) {
if (hassharp && idx> sharpindex) {
idx = sharpIndex;
} else if (haszero && idx <Zeroindex) {
idx = Zeroindex;
}
}
if (idx> -1) {
번호 = 라운드 (번호, idx);
}
} 또 다른 {
번호 = 라운드 (번호);
}
sharpIndex = format.indexof (sharp);
startzeroindex = Zeroindex = format.indexof (Zero);
// 첫 번째 자리 자리 표시 자의 인덱스를 정의합니다
if (sharpIndex == -1 && ZeroIndex! = -1) {
시작 = ZeroIndex;
} else if (sharpIndex! = -1 && ZeroIndex == -1) {
start = sharpIndex;
} 또 다른 {
start = sharpindex> Zeroindex? ZeroIndex : SharpIndex;
}
SharpIndex = format.lastIndexof (Sharp);
ZeroIndex = format.lastIndexof (Zero);
// 마지막 자리 자리 표시 자의 인덱스를 정의합니다
if (sharpIndex == -1 && ZeroIndex! = -1) {
끝 = ZeroIndex;
} else if (sharpIndex! = -1 && ZeroIndex == -1) {
끝 = sharpIndex;
} 또 다른 {
end = sharpIndex> Zeroindex? SharpIndex : Zeroindex;
}
if (start == length) {
끝 = 시작;
}
if (start! = -1) {
value = number.tostring (). split (point);
정수 = 값 [0];
fraction = value [1] || 비어 있는;
integerlength = integer.length;
fractionLength = fraction.length;
if (negative && (번호 * -1)> = 0) {
부정적인 = 거짓;
}
// 충분히 길면 그룹 분리기를 숫자에 추가합니다.
if (hasgroup) {
if (integerlength === groupsize && integerlength <decimalindex -startzeroindex) {
정수 = GroupSeparator + 정수;
} else if (integerlength> groupsize) {
값 = 빈;
for (Idx = 0; idx <integerlength; idx ++) {
if (idx> 0 && (integerlength -idx) % groupsize === 0) {
값 += GroupSeparator;
}
값 += integer.charat (idx);
}
정수 = 값;
}
}
번호 = format.substring (0, start);
if (negative &&! hasnegativeformat) {
번호 += "-";
}
for (Idx = start; idx <longth; idx ++) {
ch = format.charat (idx);
if (decimalindex == -1) {
if (end -idx <integerlength) {
번호 += 정수;
부서지다;
}
} 또 다른 {
if (Zeroindex! = -1 && Zeroindex <idx) {
교체 = 빈;
}
if ((DecimalIndex -idx) <= integerlength && decimalindex -idx> -1) {
번호 += 정수;
IDX = DECIMALINDEX;
}
if (decimalIndex === idx) {
숫자 + = (분수? 소수점 : 빈) + 분수;
idx + = end -decimalindex + 1;
계속하다;
}
}
if (ch === Zero) {
숫자 += ch;
교체 = ch;
} else if (ch === sharp) {
번호 += 교체;
}
}
if (end> = start) {
숫자 + = format.substring (end + 1);
}
// 기호 자리 표시자를 교체합니다
if (iscurrency || ispercent) {
값 = 빈;
for (idx = 0, length = number.length; idx <length; idx ++) {
ch = number.charat (idx);
value += (ch === "$"|| ch === "%")? 상징 : ch;
}
숫자 = 값;
}
길이 = 리터럴. 길이;
if (길이) {
for (Idx = 0; idx <length; idx ++) {
숫자 = number.replace (자리 표시 자, 리터럴 [idx]);
}
}
}
반품 번호;
}
var round = 함수 (값, 정밀도) {
정밀 = 정밀 || 0;
value = value.toString (). split ( 'e');
value = math.round ( + (value [0] + 'e' + (value [1]? ( + value [1] + 정밀)));
value = value.toString (). split ( 'e');
value = + (값 [0] + 'e' + (value [1]? ( + 값 [1] - 정밀) : -precision);
return value.tofixed (정밀);
};
var tostring = 함수 (값, fmt, 문화) {
if (fmt) {
if (typeof value === 번호) {
반환 형식 내버 (값, FMT, 문화);
}
}
반환 값! == 정의되지 않았습니까? 값 : "";
};
if (globaliMATED.LOAD) {
tostring = 함수 (값, 형식, 문화) {
if ($ .isplainobject (Culture)) {
문화 = 문화. 이름;
}
return globmaze.format (값, 형식, 문화);
};
}
Chopper.format = function (fmt) {
var 값 = 인수;
return fmt.replace (formatregexp, function (match, index, placeholderformat) {
var value = 값 [parseint (index, 10) + 1];
return toString (값, 위장대 Format? supholderFormat.substring (1) : "");
});
};
}) ();
</스크립트>
</body>
</html>
API :
코드 사본은 다음과 같습니다.
Chopper.format ( '{0}은 {1}', 'Xiaoming', 'Basketball')을 재생하고 있습니다. // 출력 "Xiaoming은 농구를하고 있습니다"
// 가격
Chopper.format ( '{0 : c} - {1 : c}', 10, 20); // 출력 "10.00-20.00"
// 색인
Chopper.format ( 'index : {0 : e}', 25); // 출력 "색인 : 2.5E+1"
// 퍼센트
Chopper.format ( ' % : {0 : p}', 25); // 출력 "퍼센트 : 2,500.00 %"
// 10 진
Chopper.format ( '소수 : {0 : n}', 25); // 출력 "10 진수 : 25.00"
요약:
형식 데이터는 종종 개발에 사용됩니다. 예를 들어, 변수에 따라 다른 정보를 프롬프트해야하지만 컨텐츠 템플릿은 동일 하므로이 방법을 사용할 수 있습니다. 프로젝트에서 jQuery를 사용하는 경우 위의 JavaScript를 jQuery 플러그인으로 캡슐화 할 수도 있습니다.