JavaScript equivalent to printf/String.Format

前端 未结 30 2408
囚心锁ツ
囚心锁ツ 2020-11-21 04:27

I\'m looking for a good JavaScript equivalent of the C/PHP printf() or for C#/Java programmers, String.Format() (IFormatProvider for .

30条回答
  •  无人共我
    2020-11-21 05:05

    For use with jQuery.ajax() success functions. Pass only a single argument and string replace with the properties of that object as {propertyName}:

    String.prototype.format = function () {
        var formatted = this;
        for (var prop in arguments[0]) {
            var regexp = new RegExp('\\{' + prop + '\\}', 'gi');
            formatted = formatted.replace(regexp, arguments[0][prop]);
        }
        return formatted;
    };
    

    Example:

    var userInfo = ("Email: {Email} - Phone: {Phone}").format({ Email: "someone@somewhere.com", Phone: "123-123-1234" });
    

提交回复
热议问题