JavaScript 中的字符串格式化。






4.57/5 (8投票s)
String.Format 根据模式和值创建字符串
引言
将指定 string
中的每个格式项替换为相应参数值的文本等效值。使用指定的参数值 string
表示形式替换指定 string
中的一个或多个格式项。
语法
'string with format{0}'.format(Object arg0, Object arg1, Object argn);
参数
{0}
:string
对象的类型arg0
:要格式化的第一个对象arg1
:要格式化的第二个对象argn
:要格式化的第 n 个对象
Using the Code
String.prototype.format = function () {
var args = arguments;
return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) {
if (m == "{{") { return "{"; }
if (m == "}}") { return "}"; }
return args[n];
});
};
示例
此示例演示了使用 string.Format
方法组合三个 string
以及格式化选项。格式化 string
本身是 string.Format
方法的第一个参数,它被指定为 string
字面量。
“{0}
”、“{1}
”、“{2}
”和“{N}
”指示将第一个、第二个、第三个和第 N 个参数插入到 string
对象中的位置。参数应位于 { }
方括号之间。
"Hello {0}.{1}, Welcome to our new house at {2}.".format('Mr','Imdadhusen','Ahmedabad');
输出
Hello Mr.Imdadhusen, Welcome to our new house at Ahmedabad.
更多示例
输入
var startDate = "21 APR 2014";
var endDate = "24 APR 2014";
"Your score is {0} out of {1}".format(175,250);
"Dear {0}, Your ticket is booked for {1} days from {2} to {3}.
Thank you for booking from {4}".format('Imdadhusen',4,startDate, endDate, 'www.happybooking.com');
"World T{0} - {1}th match, Group {2}, {3} v {4}, {3} won by {5} wickets
(with {6} balls remaining). {4}'s next match will be on {7}.".format
(20,13,2,'India','Pakistan', 7, 9, '25 Apr 2014');
输出
Your score is 175 out of 250
Dear Imdadhusen, Your ticket is booked for 4 days from 21 APR 2014 to 24 APR 2014.
Thank you for booking from www.happybooking.com
World T20 - 13th match, Group 2, India v Pakistan, India won by 7 wickets
(with 9 balls remaining). Pakistan's next match will be on 25 Apr 2014.
关注点
使用上述 string
工具,**您可以传递任意数量的参数,并重复参数以生成完整的字符串**。
如果您需要任何帮助,请随时告诉我。
您的宝贵反馈、评论和建议将不胜感激。