【问题标题】:Javascript equivalent to python's .format()Javascript 等价于 python 的 .format()
【发布时间】:2012-11-18 08:01:14
【问题描述】:

我想要一个模仿 python .format() 函数的 javascript 函数

.format(*args, **kwargs)

上一个问题为 '.format(*args) 提供了一个可能(但不完整)的解决方案

JavaScript equivalent to printf/string.format

我希望能够做到

"hello {} and {}".format("you", "bob"
==> hello you and bob

"hello {0} and {1}".format("you", "bob")
==> hello you and bob

"hello {0} and {1} and {a}".format("you", "bob",a="mary")
==> hello you and bob and mary

"hello {0} and {1} and {a} and {2}".format("you", "bob","jill",a="mary")
==> hello you and bob and mary and jill

我意识到这是一项艰巨的任务,但也许在某个地方有一个完整(或至少部分)的解决方案,其中也包括关键字参数。

哦,我听说 AJAX 和 JQuery 可能有这方面的方法,但我希望能够在没有所有开销的情况下做到这一点。

特别是,我希望能够将它与 google doc 的脚本一起使用。

谢谢

【问题讨论】:

  • 嗯,对这个答案很感兴趣,关注。
  • 没有内置任何东西,尽管实现起来很简单(对于一些,但不是全部,因为 JavaScript 没有“命名参数”并且指定索引手册不一样,提供的案例) .搜索“javascript printf”以获取一些潜在客户。
  • 我不相信 Javascript 默认有这样的东西。您最好尝试使用 Javascript 框架或库。如果您认为开销太大,请在 Google 上搜索“Javascript 字符串格式”,您可能会找到您喜欢的内容。
  • 你可能喜欢gist.github.com/1049426,但你可以找到更多喜欢它的人。祝您搜索愉快。

标签: javascript python string formatting string-formatting


【解决方案1】:

更新:如果您使用 ES6,模板字符串的工作方式与 String.format 非常相似:https://developers.google.com/web/updates/2015/01/ES6-Template-Strings

如果不是,以下适用于上述所有情况,其语法与 python 的 String.format 方法非常相似。下面是测试用例。

String.prototype.format = function() {
  var args = arguments;
  this.unkeyed_index = 0;
  return this.replace(/\{(\w*)\}/g, function(match, key) { 
    if (key === '') {
      key = this.unkeyed_index;
      this.unkeyed_index++
    }
    if (key == +key) {
      return args[key] !== 'undefined'
      ? args[key]
      : match;
    } else {
      for (var i = 0; i < args.length; i++) {
        if (typeof args[i] === 'object' && typeof args[i][key] !== 'undefined') {
          return args[i][key];
        }
      }
      return match;
    }
  }.bind(this));
};

// Run some tests
$('#tests')
  .append(
    "hello {} and {}<br />".format("you", "bob")
  )
  .append(
    "hello {0} and {1}<br />".format("you", "bob")
  )
  .append(
    "hello {0} and {1} and {a}<br />".format("you", "bob", {a:"mary"})
  )
  .append(
    "hello {0} and {1} and {a} and {2}<br />".format("you", "bob", "jill", {a:"mary"})
  );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tests"></div>

【讨论】:

  • \d代替\w就够了吗?
  • 不幸的是,没有。他有混合的字母和数字键。
  • 抱歉耽搁了。是的。就像你说的那样有效。干的很好。我还不知道如何在 JavaScript 中做 OO,所以这将是一个很好的例子。
  • 用智能 JS sn-p 更新。
【解决方案2】:

这应该类似于 python 的format,但对于具有命名键的对象,它也可以是数字。

String.prototype.format = function( params ) {
  return this.replace(
    /\{(\w+)\}/g, 
    function( a,b ) { return params[ b ]; }
  );
};

console.log( "hello {a} and {b}.".format( { a: 'foo', b: 'baz' } ) );
//^= "hello foo and baz."

【讨论】:

  • [^}]+ 更好?它不适用于print( "hello {a-b} and {b}.".format( { 'a-b': 'foo', b: 'baz' } ) );
  • 我很困惑你写了generic函数的用法。但这不是答案。不要介意。
  • @mattn:我不明白,你说的generic是什么意思?
  • 我很困惑你写了format function that acceptable all possible words (without {})
  • 被低估的答案
猜你喜欢
  • 1970-01-01
  • 2011-06-25
  • 1970-01-01
  • 2010-12-15
  • 2017-10-04
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
  • 2015-11-26
相关资源
最近更新 更多