フォーマットは、フォーマット操作を介してあらゆるタイプのデータを文字列に変換することです。たとえば、以下
コードコピーは次のとおりです。
<スクリプト>
console.log(chopper.format( '{0} - {1} - {2}'、12、24、25)); //出力 "12-24-25"
</script>
これは、独自のプロジェクトにコピーできる完全なコードです。
コードコピーは次のとおりです。
<!doctype html>
<html>
<head>
<meta http-equiv = "content-type" content = "text/html; charset = utf-8">
</head>
<body>
<スクリプトsrc = "http://code.jquery.com/jquery-1.9.1.min.js"> </script>
<スクリプト>
(関数() {
var Chopper = window.chopper = window.chopper || {文化:{}}、
数学=数学、
formatregexp = // {(/d+)(:[^/}]+)?/}/g、
function = "function"、
string = "string"、
number = "number"、
object = "object"、
null = "null"、
boolean = "boolean"、
未定義= "未定義"、
スライス= [] .Slice、
Globalize = window.globalize、
StandardFormatRegexp =/^(n | c | p | e)(/d*)$/i、
literalregexp = /(//.)|( [']* ['] ??(
commareGexp = //、/g、
empty = ""、
point = "。"、
comma = "、"、
sharp = "#"、
zero = "0"、
PlaceHolder = "??"、
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"、 "、"、 "、" sa "]]
}、
月:{
名前:["1月"、 "2月"、「3月」、「4月」、「5月」、「6月」、「7月」、「7月」、「8月」、「9月」、「10月」、「11月」、「12月」]、
namesabbr:["jan"、 "feb"、 "mar"、 "apr"、 "may"、 "jun"、 "aug"、 "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:「うーん、YYYY」、
Y:「うーん、YYYY」
}、
"/": "/"、
":": ":"、
初日:0、
twodigityearmax:2029
}
}
};
関数findculture(文化){
if(culture){
if(culture.numberformat){
帰りの文化;
}
if(typeof culture === string){
var Cultures = Chopper.Cultures;
文化を返す[文化] ||文化[Culture.split( " - ")[0]] ||ヌル;
}
nullを返します。
}
nullを返します。
}
関数getCulture(文化){
if(culture){
Culture = FindCulture(Culture);
}
文化を返す|| Chopper.cultures.current;
}
関数ExpandNumberFormat(numberformat){
numberformat.groupsizes = numberformat.groupsize;
numberformat.percent.groupsizes = numberformat.percent.groupsize;
numberformat.currency.groupsizes = numberformat.currency.groupsize;
}
chopper.culture = function(culturename){
var Cultures = Chopper.Cultures、Culture;
if(culturename!== undefined){
Culture = FindCulture(CultureName)||文化[en];
Culture.Calendar = Culture.Calendars.Standard;
Cultures.Current = Culture;
if(globalize &&!globalize.load){
ExpandNumberFormat(Culture.NumberFormat);
}
} それ以外 {
return cultures.current;
}
};
Chopper.Culture(en);
//番号フォーマット
function formatnumber(number、format、culture){
Culture = GetCulture(Culture);
var numberformat = culture.numberformat、
グループ化= numberformat.groupsize [0]、
GroupSeparator = numberformat [comma]、
Decimal = numberformat [point]、
精密= numberformat.decimals、
パターン= numberformat.pattern [0]、
リテラル= []、
シンボル、
iscurrency、ispercent、
CustomPrecision、
formatandprecision、
ネガティブ=数<0、
整数、
分数、
integerlength、
fractionlength、
交換=空、
値=空、
idx、
長さ、
ch、
Hasgroup、
HasNegativeFormat、
decimalindex、
SharpIndex、
ZeroIndex、
Haszero、Hassharp、
パーセントインデックス、
CurrencyIndex、
startzeroindex、
start = -1、
終わり;
//番号がない場合は空の文字列を返します
if(number === undefined){
空に戻ります。
}
if(!isfinite(number)){
返品番号。
}
//フォーマットがない場合、number.toString()またはnumber.tolocalestring()を返します。culture.nameが定義されていない場合
if(!format){
return Culture.name.length? number.tolocalestring():number.toString();
}
formatandprecision = StandardFormatregexp.exec(format);
//標準フォーマット
if(formatandprecision){
format = formatandprecision [1] .tolowercase();
iscurrency = format === "c";
ispercent = format === "p";
if(iscurrency || ispercent){
//フォーマットが通貨またはパーセントである場合、特定の番号形式情報を取得します
numberformat = iscurrency? numberformat.currency:numberformat.percent;
グループ化= numberformat.groupsize [0];
GroupSeparator = numberformat [comma];
Decimal = numberformat [point];
Precision = numberformat.decimals;
Symbol = numberformat.symbol;
pattern = numberformat.pattern [ネガ? 0:1];
}
customprecision = formatandprecision [2];
if(customprecision){
Precision = +CustomPrecision;
}
//指数形式で番号を返します
if(format === "e"){
カスタムプレシジョンを返しますか? number.toexponential(precision):number.toexponential(); // ff#653438で異なるtoexponential()およびtoexponential(未定義)。
}
//フォーマットがパーセントの場合は乗算します
if(ispercent){
番号 *= 100;
}
number = round(number、precision);
ネガティブ= number <0;
number = number.split(point);
integer = number [0];
fraction = number [1];
//除外 " - "数字が負の場合。
if(否定){
integer = integer.substring(1);
}
value = integer;
integerlength = integer.length;
//十分に長い場合は、グループ分離器を数に追加します
if(integerlength> =グループ化){
value = empty;
for(idx = 0; idx <integerlength; idx ++){
if(idx> 0 &&(integerlength -idx)%グループ=== 0){
value += GroupSeparator;
}
value += integer.charat(idx);
}
}
if(fraction){
値 + =小数 +分率。
}
if(format === "n" &&!否定){
返品値。
}
number = empty;
for(idx = 0、length = pattern.length; idx <length; idx ++){
ch = pattern.charat(idx);
if(ch === "n"){
番号 +=値;
} else if(ch === "$" || ch === "%"){
番号 += symbol;
} それ以外 {
番号 += ch;
}
}
返品番号。
}
//カスタムフォーマット
//
//セクションごとに個別の形式。
//番号を正しくします
if(否定){
number = -number;
}
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(quoteChar、 "");
literals.push(リテラル);
戻りプレースホルダー。
});
}
format = format.split( ";");
if(negative && format [1]){
//ネガティブ形式を取得します
format = format [1];
HasNegativeFormat = true;
} else if(number === 0){
// Zerosの形式
Format = Format [2] ||フォーマット[0];
if(format.indexof(sharp)== -1 && format.indexof(zero)== -1){
//文字列定数の場合はフォーマットを返します。
返品形式。
}
} それ以外 {
format = format [0];
}
percentIndex = format.indexof( "%");
CurrencyIndex = format.indexof( "$");
ispercent = percentIndex!= -1;
iscurrency = currencyindex!= -1;
//フォーマットにパーセントがある場合は、番号を掛けます
if(ispercent){
番号 *= 100;
}
if(iscurrency && format [currencyindex -1] === "//"){
format = format.split( "//")。join( "");
iscurrency = false;
}
if(iscurrency || ispercent){
//フォーマットが通貨またはパーセントである場合、特定の番号形式情報を取得します
numberformat = iscurrency? numberformat.currency:numberformat.percent;
グループ化= 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]));
} それ以外 {
分数= fraction [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);
length = format.length;
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){
number = round(number、idx);
}
} それ以外 {
number = round(number);
}
SharpIndex = format.indexof(sharp);
startzeroindex = zeroindex = format.indexof(zero);
//最初の桁のプレースホルダーのインデックスを定義します
if(sharpindex == -1 && zeroindex!= -1){
start = 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){
end = zeroindex;
} else if(sharpindex!= -1 && zeroindex == -1){
end = sharpindex;
} それ以外 {
end = sharpindex> zeroindex? SharpIndex:ZeroIndex;
}
if(start == length){
end = start;
}
if(start!= -1){
value = number.toString()。split(point);
integer = value [0];
fraction = value [1] ||空の;
integerlength = integer.length;
fractionlength = fraction.length;
if(negial &&(number * -1)> = 0){
ネガティブ= false;
}
//十分に長い場合は、グループ分離器を数に追加します
if(hasgroup){
if(integerlength ===グループ化&& integerlength <decimalindex -startzeroindex){
integer = groupseparator + integer;
} else if(integerlength>グループ化){
value = empty;
for(idx = 0; idx <integerlength; idx ++){
if(idx> 0 &&(integerlength -idx)%グループ=== 0){
value += GroupSeparator;
}
value += integer.charat(idx);
}
integer = value;
}
}
number = format.substring(0、start);
if(negial &&!hasnegativeformat){
番号 += " - ";
}
for(idx = start; idx <length; idx ++){
ch = format.charat(idx);
if(decimalindex == -1){
if(end -idx <integerlength){
番号 += integer;
壊す;
}
} それ以外 {
if(zeroindex!= -1 && zeroindex <idx){
交換=空;
}
if((decimalindex -idx)<= integerlength && decimalindex -idx> -1){
番号 += integer;
idx = decimalindex;
}
if(decimalindex === idx){
number + =(fraction?decimal:empt) + fraction;
idx + = end -decimalindex + 1;
続く;
}
}
if(ch === zero){
番号 += ch;
交換= ch;
} else if(ch === sharp){
番号 +=交換;
}
}
if(end> = start){
番号 + = format.substring(end + 1);
}
//シンボルプレースホルダーを交換します
if(iscurrency || ispercent){
value = empty;
for(idx = 0、length = number.length; idx <length; idx ++){
ch = number.charat(idx);
value +=(ch === "$" || ch === "%")?シンボル:ch;
}
number = value;
}
length = leterals.length;
if(length){
for(idx = 0; idx <length; idx ++){
number = number.replace(プレースホルダー、リテラル[idx]);
}
}
}
返品番号。
}
var round = function(value、precision){
精度=精度|| 0;
value = value.toString()。split( 'e');
value = math.round( +(value [0] + 'e' +(value [1]?( + value [1] + precision):precision)));
value = value.toString()。split( 'e');
value = +(value [0] + 'e' +(value [1]?( + value [1] - precision): - precision));
return value.tofixed(precision);
};
var toString = function(value、fmt、culture){
if(fmt){
if(typeof value === number){
return formatnumber(value、fmt、culture);
}
}
return値!== undefined?価値 : "";
};
if(globalize &&!globalize.load){
toString = function(value、format、culture){
if($ .isplainobject(culture)){
Culture = Culture.Name;
}
Globalize.Format(Value、Format、Culture)を返します。
};
}
chopper.format = function(fmt){
var値=引数;
return fmt.Replace(formatregexp、function(match、index、placeholderformat){
var値=値[parseint(index、10) + 1];
returtring(value、placeholderformat?placeholderformat.substring(1): "");
});
};
})();
</script>
</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%」
// Decimal
chopper.format( 'decimal:{0:n}'、25); //出力 "Decimal:25.00"
まとめ:
フォーマットデータは、多くの場合、開発で使用されます。たとえば、変数に応じて異なる情報をプロップする必要がありますが、コンテンツテンプレートは同じであるため、この方法を使用できます。プロジェクトがjQueryを使用している場合は、上記のJavaScriptをjQueryプラグインにカプセル化することもできます。