Javascript equivalent to python's .format()

六月ゝ 毕业季﹏ 提交于 2019-11-27 21:37:16

UPDATE: If you're using ES6, template strings work very similarly to String.format: https://developers.google.com/web/updates/2015/01/ES6-Template-Strings

If not, the below works for all the cases above, with a very similar syntax to python's String.format method. Test cases below.

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>

This should work similar to python's format but with an object with named keys, it could be numbers as well.

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."
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!