JavaScript相当于Python的format()函数?

Ble*_*der 46 javascript python format

Python有这个美丽的功能来解决这个问题:

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

foo = 'The lazy ' + bar3 + ' ' + bar2 ' over the ' + bar1
# The lazy dog jumped over the foobar
Run Code Online (Sandbox Code Playgroud)

进入:

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

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

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

CMS*_*CMS 49

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

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"
Run Code Online (Sandbox Code Playgroud)

  • 是的,有道理.http://jsfiddle.net/wFb2p/6/我以前没有意识到该功能每次匹配都会运行一次.+1 (2认同)
  • 使用替换函数也意味着您可以非常轻松地扩展它以支持非空占位符,例如`{1}`. (2认同)

Yas*_*tra 24

有一种方法,但不完全使用格式.

var name = "John";
var age = 19;
var message = `My name is ${name} and I am ${age} years old`;
console.log(message);
Run Code Online (Sandbox Code Playgroud)

jsfiddle - 链接

  • 这确实解决了问题,如果你没有上下文,你可以轻松地做一些事情,比如```var message =`我的名字是$ {name || 'default'}我是$ {age || 'default'}岁了!```` (4认同)
  • @shrewmouse:或者只是`f'我的名字是{name}而我在Python 3.6中是{age}'`. (4认同)
  • 这一切都很有趣,但这并没有解决问题.如果我们不能将ES6传递给特定的上下文,那么ES6中的方法在很多情况下都是毫无意义的.你写的主要是字符串连接的语法糖. (2认同)
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals (2认同)

小智 10

寻找同一个问题的答案,我刚刚发现了这个:https://github.com/davidchambers/string-format,这是"受Python启发的JavaScript字符串格式str.format()".它似乎与python的format()功能几乎相同.


Cor*_*lex 10

tl; dr

foo = (a, b, c) => `The lazy ${a} ${b} over the ${c}`
Run Code Online (Sandbox Code Playgroud)

为什么仅模板字符串还不够

ES6 模板字符串提供的功能与pythons字符串格式非常相似。但是,在构造字符串之前,您必须了解变量:

var templateString = `The lazy ${bar3} ${bar2} over the ${bar1}`;
Run Code Online (Sandbox Code Playgroud)

为什么要格式化?

Python str.format允许您甚至不知道要插入哪个值之前就指定字符串,例如:

foo = 'The lazy {} {} over the {}'

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

foo.format(bar3, bar2, bar1)
Run Code Online (Sandbox Code Playgroud)

使用arrow函数,我们可以优雅地包装模板字符串以供以后使用:

foo = (a, b, c) => `The lazy ${a} ${b} over the ${c}`

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

foo(bar3, bar2, bar1)
Run Code Online (Sandbox Code Playgroud)

当然,这也可以与常规功能一起使用,但是箭头功能使我们可以使其成为单线。这两种功能在大多数浏览器和运行时中都可用:

  • 这错过了使用 xx.format() 的一个主要原因,与 @Yash Mehrotra 的答案具有相同的缺点,即要格式化的字符串可能需要是动态的而不是硬编码的。 (2认同)
  • 这应该是最重要的答案。谢谢你! (2认同)

小智 6

您可以在 JS 中使用模板文字,

const bar1 = 'foobar'
const bar2 = 'jumped'
const bar3 = 'dog'
foo = `The lazy ${bar3} ${bar2} over the ${bar1}`
Run Code Online (Sandbox Code Playgroud)

我认为这很有帮助。


Pat*_*and 5

取自YAHOOs图书馆:

YAHOO.Tools.printf = function() { 
  var num = arguments.length; 
  var oStr = arguments[0];   
  for (var i = 1; i < num; i++) { 
    var pattern = "\\{" + (i-1) + "\\}"; 
    var re = new RegExp(pattern, "g"); 
    oStr = oStr.replace(re, arguments[i]); 
  } 
  return oStr; 
} 
Run Code Online (Sandbox Code Playgroud)

称之为:

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

foo = YAHOO.Tools.printf('The lazy {0} {1} over the {2}', bar3, bar2, bar1); 
Run Code Online (Sandbox Code Playgroud)