String 增加格式化

1 篇文章 / 0 new
author
String 增加格式化
sffjs 提供一組 String.format() 功能的擴充 js, 操作方式雷同 .Net 的 String.format
引入
<script type="text/javascript" src="stringformat-X.XX.min.js"></script>
<script type="text/javascript" src="cultures/stringformat.en.js"></script>
<script type="text/javascript" src="cultures/stringformat.sv.js"></script>
語法參考
// Object path
String.format("Welcome back, {username}!", 
{ id: 3, username: "JohnDoe" });
// Result: "Welcome back, JohnDoe!"
 
// Date/time formatting
String.format("The time is now {0:t}.", new Date(2009, 5, 1, 13, 22));
// Result: "The time is now 01:22 PM."
 
// Date/time formatting (without using a full format string)
var d = new Date();
d.format("hh:mm:ss tt");
// Result: "02:28:06 PM"
 
// Custom number format string
String.format("Please call me at {0:+##0 (0) 000-00 00}.", 4601111111);
// Result: "Please call me at +46 (0) 111-11 11."
 
// Another custom number format string
String.format("The last year result was {0:+$#,0.00;" + "-$#,0.00;0}.", -5543.346);
// Result: "The last year result was -$5,543.35."
 
// Alignment
String.format("|{0,10:PI=0.00}|", Math.PI);
// Result: "|   PI=3.14|"
 
// Rounding
String.format("1/3 ~ {0:0.00}", 1/3);
// Result: "1/3 ~ 0.33"
 
// Boolean values
String.format("{0:true;;false}", 0);
// Result: "false"
 
// Explicitly specified localization
// (note that you have to include the .js file for used cultures)
sffjs.setCulture("en-US");
String.format("{0:#,0.0}", 3641.667);
// Result: "3,641.7"
 
sffjs.setCulture("sv-SE");
String.format("{0:#,0.0}", 3641.667);
// Result: "3 641,7"
Free Web Hosting