xinxin-csharp

一直用C#编程,在日常字符串拼接中string.Format()一直是个很好用很常用的方法,不用自己+++,既影响开发效率也影响可读性

然而在js中并没有这样的函数可供使用,so整理了一个js的字符串format函数供项目的日常使用

虽然并不是很完善也不能提升拼接效率,但是足够满足开发过程中的工作效率和可读性

 

通过String类型的原型prototype新增一个format方法,方便使用

String.prototype.format = function () {
    if (arguments.length === 0) return this;
    var result = this;
    if (arguments.length === 1 && typeof arguments[0] === \'object\') {
        for (var key in arguments[0]) {
            if (arguments[0][key] === undefined) continue;
            result = result.replace(new RegExp("({" + key + "})", "g"), arguments[0][key]);
        }
    } else {
        for (var i = 0; i < arguments.length; i++) {
            if (arguments[i] === undefined) continue;
            result = result.replace(new RegExp("({[" + i + "]})", "g"), arguments[i]);
        }
    }
    return result.toString();
}

测试一下:

\'Welcome to {city}! My name is {name}.\'.format({ city: \'阜宁\', name: \'恋禾梦颖\' });
\'Total num is {0},total price is ${1}\'.format(2, 10);

测试结果:

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-01-04
  • 2021-11-23
  • 2021-09-16
  • 2021-08-24
  • 2021-06-05
  • 2021-09-19
  • 2022-01-07
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-02-02
  • 2022-02-08
  • 2021-12-02
  • 2021-05-31
  • 2021-11-03
相关资源
相似解决方案