使用js在HTML中自定义字符串格式化方法

Python中支持字符串格式化,其基本形式如下:

1 str = "I'm {name},{age} years old"
2 print(str.format(name="test", age=19))
3 
4 
5 """
6 结果
7 I'm test,19 years old
8 """

在JavaScript中虽没有类似的方法,但我们可以利用字符串的replace方法自定义字符串的格式化方法:

 1 <script>
 2     $(function () {
 3             /*自定义字符串格式化*/
 4         String.prototype.Format = function (args) {
 5             /*this代表要调用Format方法的字符串*/
 6             /*replace的第一个参数为正则表达式,g表示处理匹配到的所有字符串,在js中使用//包起来*/
 7             /*replace的第二个参数为匹配字符串的处理,k1匹配结果包含{},k2只保留{}内的内容*/
 8             var temp = this.replace(/{(w+)}/g, function (k1, k2) {
 9                 console.log(k1, k2);
10                 /*replace将匹配到的k2用参数args替换后赋给新变量temp*/
11                 return args[k2];
12             });
13             /*自定义方法Format将格式化后的字符串返回*/
14             return temp;
15         };
16     }
17 </script>

验证:

原文地址:https://www.cnblogs.com/OldJack/p/7210280.html