sprintf() for JavaScript 的行为类似于 Python 的格式 (%)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5675001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:23:43  来源:igfitidea点击:

sprintf() for JavaScript that behaves like Python's format (%)?

javascriptjqueryprintf

提问by Rory

I need a JavaScript function (or jQuery plugin) for printf/sprintf. It needs to support named arguments ("%(foo)s") and padding ("%02d"), i.e.the following format string should work:

我需要一个用于printf/的 JavaScript 函数(或 jQuery 插件)sprintf。它需要支持命名参数 ( "%(foo)s") 和填充 ( "%02d"),以下格式字符串应该可以工作:

"%(amount)s.%(subunits)02d"

It only needs to support sand d, I don't care about all the other format strings (e.g. f, x, etc.). I don't need padding for strings/s, just d, I only need simple padding for d, e.g. %2d, %3d, %04d, etc.

它只需要支持sd,我不关心其他所有的格式字符串(例如fx等)。我不需要为字符串填充/ s,只是d,我只需要简单填充d,如%2d%3d%04d,等。

回答by diEcho

A previous question "Javascript printf/string.format" has some good information.

上一个问题“ Javascript printf/string.format”有一些很好的信息。

Also, dive.into.javascript() has a pageabout sprintf().

此外,dive.into.javascript() 有一个关于sprintf().

回答by Spudley

The PHPJS project has implemented a lot of PHP's functionality in Javascript. I can't imagine why they'd want to do that, but the fact remains that they have produced a sprintf()implementation which should satisfy your needs (or at least come close).

PHPJS 项目已经在 J​​avascript 中实现了很多 PHP 的功能。我无法想象他们为什么要这样做,但事实仍然是他们已经生成了一个sprintf()应该满足您的需求(或至少接近)的实现。

Code for it can be found here: http://phpjs.org/functions/sprintf

它的代码可以在这里找到:http: //phpjs.org/functions/sprintf

回答by Elvis Reyes

Here one function

这里有一个功能

var sprintf = function(str) {
  var args = arguments,
    flag = true,
    i = 1;

  str = str.replace(/%s/g, function() {
    var arg = args[i++];

    if (typeof arg === 'undefined') {
      flag = false;
      return '';
    }
    return arg;
  });
  return flag ? str : '';
};

$(document).ready(function() {

  var msg = 'the department';

  $('#txt').html(sprintf('<span>Teamwork in </span> <strong>%s</strong>', msg));

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<center id="txt"></center>