首頁 > web前端 > js教程 > 主體

使用js實作資料格式化_javascript技巧

WBOY
發布: 2016-05-16 16:29:25
原創
1400 人瀏覽過

格式化是透過格式操作使任意類型的資料轉換成一個字串。例如下面這樣

複製程式碼 程式碼如下:

<script><br /> console.log(chopper.format('{0} - {1} - {2}', 12, 24, 25)); // outputs "12 - 24 - 25"<br /> </script>

下面是一個完整的程式碼,可以複製到自己的專案中。

複製程式碼 程式碼如下:

 
 
    
        
     頭>
    
         >
        
         (函數() {
             var 斬波器 = window.chopper = window.chopper || { 文化:{} },
                 數學=數學,
                 formatRegExp = /{(d )(:[^}] )?}/g,
                 FUNCTION = "函數",
                 STRING = "字串",
                 NUMBER =“數位”,
                 OBJECT = "物件",
                 NULL = "空白",
                 BOOLEAN =“布林值”,
                 UNDEFINED = "未定義",
                 切片 = [].slice,
                 globalize = window.Globalize,
                 standardFormatRegExp = /^(n|c|p|e)(d*)$/i,
                 literalRegExp = /(\.)|(['][^']*[']?)|(["][^"]*["]?)/g                  逗號RegExp = /,/g,
                 空白 = "",
                 點=“。”,
                 逗號 = ",",
                 夏普 = "#",
                 零=“0”,
                 佔位符=“??”,
                 EN =“en-US”,
                 objectToString = {}.toString;
             //文化
             chopper.cultures["en-US"] = {
                 名稱:EN,
                 數位格式:{
                     模式:[「-n」],
                     小數: 2,
                     ",": ",",
                     ".": ".",
                     類大小:[3],
                     百分比:{
                         模式:[「-n %」,「n %」],
                         小數: 2,
                         "、": ",",
                         ".": ".",
                         類大小:[3],
                         符號與「%」
                     },
                     貨幣:{
                         模式:["($n)", "$n"],
                         小數: 2,
                         "、": ",",
                         ".": ".",
                         類大小:[3],
                         符號:「$」
                     }
                 },
                 行事曆:{
                     標準:{
                         天:{
                             名稱:[「星期日」、「星期一」、「星期二」、「星期三」、「星期四」、「星期三」、「星期六」、「星期五」、「星期四」、「星期三」、「星期四」、「星期五」、「星期六」、「星期五」、「星期四」                              nameAbbr:[「週日」,「週一」,「週二」,「週三」,「週四」,「週五」,「週日」                 地                          },
                         月份:{
名稱:[「一月」、「二月」、「三月」、「四月」、「五月」、「六月」、「七月」、「八月」、「九月」、「十月」、「十一月」、「十二月」 ],
名稱縮寫:[“一月”,“二月”,“三月”,“四月”,“五月”,“六月”,“七月”,“八月”,“九月”,“十月”,“十一月”,“十二月” ]
                         },
                         以「上午」,「上午」,「上午」],
                         的「下午」,「下午」,「下午」],
                        模式:{
                             d: "月/日/年",
                             D:「dddd,MMMM dd,yyyy」,
                             F: "dddd, MMMM dd, yyyy h:mm:ssss",
                             g: "月/日/年 h:mm tt",
                             G:「年月日時:分:秒 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,
                         以雙數年最大:2029
                     }
                 }
             };
              函數 findCulture(文化) {
                 若(文化){
                     if (culture.numberFormat) {
                        迴歸文化;
                     }
                     if (文化型態 === STRING) {
                         var 文化 = chopper.cultures;
                         返回文化中[文化] ||文化[culture.split("-")[0]] ||;
                     }
                     回空;
                 }
                 回空;
             }
             函數 getCulture(文化) {
                 若(文化){
                     文化化 = findCulture(文化);
                 }
                 迴歸文化|| 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 文化 = chopper.cultures, 文化;
                 if (cultureName !== undefined) {
                                          culture.calendar =culture.calendars.standard;
                     Cultures.current = 文化化;
                     if (全球 && !globalize.load) {
                         ExpandNumberFormat(culture.numberFormat);
                     }
                 } 其他 {
                     回 cultures.current;
                 }
             };
             chopper.culture(EN);
             //數位格式
             函數 formatNumber(數位、格式、文化) {
                 文化 = getCulture(文化);
                 var numberFormat =culture.numberFormat,
                     groupSize = numberFormat.groupSize[0],
                     groupSeparator = numberFormat[COMMA],
                    且小數 = numberFormat[POINT],
                     precision = numberFormat.decimals,
                     模式 = numberFormat.pattern[0],
                     文字 = [],
                     符號,且
                     isCurrency, isPercent,
                     自訂精確度,
                     格式且精確度,
                     負數=數                      整數,
                     分數,且
                     整數長度,
                     分數長度,且
                     替換者=空,
                     值=空,且
                     idx,
                     長度,且
                     ch,
                     有組,且
                    ,
                     小數索引,
                     銳利指數,
                     零索引,
                     有零,且有夏普,
                     百分比索引,
                     金錢指數,且
                     以開始於零索引,
                     開始 = -1,
                     結束;
                 //若沒有數位則回空字串
                 if (數位 ===未定義) {
                     回空;
                 }
                 if (!isFinite(number)) {
                    且有編號;
                 }
                 //若沒有格式則回傳number.toString()或number.toLocaleString()若未定義culture.name
                 if (!format) {
                     以文化名稱.長度? number.toLocaleString() : number.toString();
                 }
                 formatAndPrecision = standardFormatRegExp.exec(format);
                 // 標準格式
                 if (formatAndPrecision) {
                     格式 = formatAndPrecision[1].toLowerCase();
                     isCurrency = format === "c";
                     isPercent = format === "p";
                     if (isCurrency || isPercent) {
                         //若格式為貨幣或百分比,則以特定的數位格式資訊
                         數位格式 = 金錢? numberFormat.currency : numberFormat.percent;
                         groupSize = numberFormat.groupSize[0];
                         groupSeparator = numberFormat[COMMA];
                         小數 = numberFormat[POINT];
                         precision = numberFormat.decimals;
                         符號 = numberFormat.symbol;
                        模式 = numberFormat.pattern[負數? 0 : 1];
                     }
                     customPrecision = formatAndPrecision[2];
                     if (customPrecision) {
                        精確度 = 自訂精確度;
                     }
                     //以指數型態回報數位
                     if (format === "e") {
                         以回復方式為精確度? number.toExponential(精度) : number.toExponential(); // toExponential() 和 toExponential(undefined) 在 FF 中有所不同 #653438.
                     }
                     // 以百分比為百分比則相乘
                     if (isPercent) {
                         數量 *= 100;
                     }
                     數位 = round(數位, 精確度);
                     負數=數                      number = number.split(POINT);
                     整數 = 數位[0];
                     分數 = 數位[1];
                     //以負數則排除「-」。
                     若(負){
                         整數 = 整數.子字串(1);
                     }
                     為 整數;
                     整數長度 = 整數.長度;
                     //若數字夠長,而新增組分隔符號
                     if (integerLength >= groupSize) {
                         值=空格;
                         for (idx = 0; idx                             if if (idx > 0 && (integerLength - idx) % comize === 0) {;                              }
                             value = integer.charAt(idx);
;
;                          }
                     }
                     若(分數){
                         值=小數;
                     }
                     if (格式 === "n" && !負數) {
                         回復值;
                     }
                     數=空白;
                     for (idx = 0, length = pattern.length; idx                          ch = pattern.charAt(idx);
                         if (ch === "n") {
                            且數 = 值;
                         } else if (ch === "$" || ch === "%") {
                             數 = 符號化;
                         } 其他 {
                             數位 = ch;
                         }
                     }
                    且有編號;
                 }
                 //自訂格式
                 //
                 //以部分分隔格式。
                 //使數位為正值
                 若(負){
                     數位 = -數位;
                 }
                 if (format.indexOf("'") > -1 || format.indexOf(""") > -1 || format.indexOf("\") > -1) {
                    為mat = format.replace(literalRegExp, function (match) {
                         var quoteChar = match.charAt(0).replace("\", ""),
match.charAt(0).replace("\", ""),
match.charAt(0).replace("\", ""),
match.charAt(0).replace("\", ""),
match.charAt(0).replace("\", ""),
                             literal = match.slice(1).replace(quoteChar,"))
;;;;;;;;;;;;;;;;;;;;                          Literals.push(literal);                          回復所佔位符;                      });                  }                 format = format.split(";");
                 if (負數 && 格式[1]) {
                     //以負數格式
                     格式 = 格式[1];
                     有NegativeFormat = true;
                 } else if (number === 0) {
                     //零的格式
                     格式=格式[2] ||格式[0];
                     if (format.indexOf(SHARP) == -1 && format.indexOf(ZERO) = -1) {
                         //若為字串常數則回傳格式
                        且為「🎜>                      }
                 } 其他 {
                     格式 = 格式[0];
                 }
                 percentIndex = format.indexOf("%");
                 currencyIndex = format.indexOf("$");
                 isPercent = PercentIndex != -1;
                 isCurrency = 貨幣指標 != -1;
                 //若有百分比
,乘以數字                  if (isPercent) {
                     數量 *= 100;
                 }
                 if (isCurrency && format[currencyIndex - 1] === "\") {
                    以對中為mat.split("
\").join("");                      isCurrency = false;
                 }
                 if (isCurrency || isPercent) {
                     //若格式為為金錢或百分比,則以特定的數位格式資訊
                     數位格式 = 金錢? numberFormat.currency : numberFormat.percent;
                     groupSize = numberFormat.groupSize[0];
                     groupSeparator = numberFormat[COMMA];
                    且小數 = numberFormat[POINT];
                     precision = numberFormat.decimals;
                     符號 = numberFormat.symbol;
                 }
                 hasGroup = format.indexOf(COMMA) > > -1;
                 if (hasGroup) {
                     format = format.replace(commaRegExp, EMPTY);
                 }
                 DecimalIndex = format.indexOf(POINT);
                 長度 = 格式.長度;
                 if (decimalIndex != -1) {
                     分數 = number.toString().split("e");
                     if (分數[1]) {
                         分數 = round(數位, Math.abs(分數[1]));
                     } 其他 {
                         分數 = 分數[0];
                     }
                     分數 =fraction.split(POINT)[1] ||空;
                    在中如對下為mat.lastIndexOf(ZERO) - 小數指標;
                     SharpIndex = format.lastIndexOf(SHARP) - 小數索引;
                     hasZero = 零指數 > -1;
                     有Sharp=sharpIndex>; -1;
                     idx = 分數.長度;
                     if (!hasZero && !hasSharp) {
                         format = format.substring(0, DecimalIndex) format.substring(decimalIndex 11);                         長度且為長度;
                         小數指標 = -1;
                         idx = 0;
                     } if (hasZero && ZeroIndex > SharpIndex) {
                         idx = 零指標;
                     } else if (sharpIndex > ZeroIndex) {
                         if (hasSharp && idx > SharpIndex) {
                             idx = SharpIndex;
                         } else if (hasZero && idx                              idx = 零指數;
;
;                          }
                     }
                     if (idx > -1) {
                         數位 = round(數位, idx);
                     }
                 } 其他 {
                     數位 = 輪次(數);
                 }
                 SharpIndex = format.indexOf(SHARP);
                 startZeroIndex = ZeroIndex = format.indexOf(ZERO);
                 //定義第一個數位佔位符的指標
                 if (sharpIndex == -1 && ZeroIndex != -1) {
                     開始=零索引;
                 } else if (sharpIndex != -1 && ZeroIndex == -1) {
                     開始 = SharpIndex;
                 } 其他 {
                     開始 = SharpIndex >零指標?零索引:銳利索引;
                 }
                 SharpIndex = format.lastIndexOf(SHARP);
                 ZeroIndex = format.lastIndexOf(ZERO);
                 //定義最後一位佔位符的指標
                 if (sharpIndex == -1 && ZeroIndex != -1) {
                     結束=零索引;
                 } else if (sharpIndex != -1 && ZeroIndex == -1) {
                     結束=銳利索引;
                 } 其他 {
                     結束=銳利指數>零指數?銳利索引:零索引;
                 }
                 if (開始 == 長度) {
                     結束=開始;
                 }                 if (開始!= -1) {
                     value = number.toString().split(POINT);
                     整數 = 值[0];
                     分數 = 值[1] ||空白;
                     整數長度 = 整數.長度;
                     fractionLength =fraction.length;
                     if (負數 && (數 * -1) >= 0) {
                        且為負=假;
                     }
                     //若數字夠長,而新增組分隔符號
                     if (hasGroup) {
                         if (integerLength === groupSize && integerLength                             整數 = 群分隔子整數;
                         } else if (integerLength > groupSize) {
                             值=空格(
                             for (idx = 0; idx                                                                     地                                  }
                                 value = integer.charAt(idx);
;
;
;
;
;
;
;
;
;
;
;
;                              }                              整數 = 值;                          }                      }                      number = format.substring(0, start);                      if (負 && !hasNegativeFormat) {                          數 = "-";                      }                     for (idx = 開始; idx                          ch = format.charAt(idx);
                         if (decimalIndex = -1) {
                            if (end - idx                                                                  且休息;
                             }
                         } 其他 {
                            if (zeroIndex != -1 && ZeroIndex                                 )使用且為空格;
                             }
                             if ((decimalIndex - idx) -11) {= 小數指標                                                                                                }
                            if (decimalIndex === idx) {
                                                                                                   續中;
                             }
                         }
                         if (ch === 0) {
                             數位 = ch;
                             替換為 = ch;
                         } else if (ch === SHARP) {
                             番号 = 置換;
                         }
                     }
                     if (終了 >= 開始) {
                         数値 = format.substring(end 1);
                     }
        
相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板