您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

相当于python的.format()的Javascript

相当于python的.format()的Javascript

更新:如果您使用的是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>
python 2022/1/1 18:36:06 有226人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶