JavaScript 等效于 Python 的 format() 函数? [英] JavaScript equivalent of Python's format() function?

查看:7

问题描述

Python 有一个漂亮的函数来转这个:

Python has this beautiful function to turn this:

bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'

foo = 'The lazy ' + bar3 + ' ' + bar2 ' over the ' + bar1
# The lazy dog jumped over the foobar

进入这个:

bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'

foo = 'The lazy {} {} over the {}'.format(bar3, bar2, bar1)
# The lazy dog jumped over the foobar

JavaScript有这样的功能吗?如果不是,我将如何创建一个遵循与 Python 实现相同的语法?

Does JavaScript have such a function? If not, how would I create one which follows the same syntax as Python's implementation?

推荐答案

另一种方法,使用 String.prototype.replace 方法,第二个参数是replacer"函数:

Another approach, using the String.prototype.replace method, with a "replacer" function as second argument:

String.prototype.format = function () {
  var i = 0, args = arguments;
  return this.replace(/{}/g, function () {
    return typeof args[i] != 'undefined' ? args[i++] : '';
  });
};

var bar1 = 'foobar',
    bar2 = 'jumped',
    bar3 = 'dog';

'The lazy {} {} over the {}'.format(bar3, bar2, bar1);
// "The lazy dog jumped over the foobar"
查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆