zoukankan      html  css  js  c++  java
  • 使用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>

    验证:

  • 相关阅读:
    情人节玫瑰花
    Yii2美化confirm
    apache ab压力测试
    Yii2的Debug工具
    yii2的扩展程序包
    slim
    composer使用
    打印
    yii的csv导出
    ajax文件下载
  • 原文地址:https://www.cnblogs.com/OldJack/p/7210280.html
Copyright © 2011-2022 走看看