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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4974238/
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-18 18:24:17  来源:igfitidea点击:

JavaScript equivalent of Python's format() function?

javascriptpythonformat

提问by Blender

Python has this beautiful function to turn this:

Python 有一个漂亮的函数来改变这个:

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

foo = 'The lazy ' + bar3 + ' ' + bar2 ' over the ' + bar1
# The lazy dog jumped over the foobar

Into this:

进入这个:

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

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

Does JavaScript have such a function? If not, how would I create one which follows the same syntax as Python's implementation?

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

采纳答案by CMS

Another approach, using the String.prototype.replacemethod, with a "replacer" function as second argument:

另一种方法,使用该String.prototype.replace方法,将“替换器”函数作为第二个参数:

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"

回答by PatrikAkerstrand

Taken from YAHOOs library:

摘自雅虎图书馆:

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; 
} 

Call it like:

像这样称呼它:

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

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

回答by typo.pl

JavaScript doesn't have such a function AFAIK.

JavaScript 没有这样的功能 AFAIK。

You could create one by modifying the String class's prototype object to add a format() method which takes a variable number of arguments.

您可以通过修改 String 类的原型对象来添加一个 format() 方法,该方法采用可变数量的参数来创建一个。

In the format method you'd have to get the String's instance value (the actual string) and then parse it for '{}' and insert the appropriate argument.

在 format 方法中,您必须获取 String 的实例值(实际字符串),然后将其解析为 '{}' 并插入适当的参数。

Then return the new string to the caller.

然后将新字符串返回给调用者。

回答by user113716

Here's my first attempt. Feel free to point out flaws.

这是我的第一次尝试。欢迎指出不足之处。

Example:http://jsfiddle.net/wFb2p/5/

示例:http : //jsfiddle.net/wFb2p/5/

String.prototype.format = function() {
    var str = this;
    var i = 0;
    var len = arguments.length;
    var matches = str.match(/{}/g);
    if( !matches || matches.length !== len ) {
        throw "wrong number of arguments";
    }
    while( i < len ) {
        str = str.replace(/{}/, arguments[i] );
        i++;
    }
    return str;
};


EDIT:Made it a bit more efficient by eliminating the .match()call in the whilestatement.

编辑:通过消除语句中的.match()调用使其效率更高while

EDIT:Changed it so that the same error is thrown if you don't pass any arguments.

编辑:更改它以便在您不传递任何参数时抛出相同的错误。

回答by zzzzBov

JavaScript does not have a string formatting function by default, although you can create your own or use one someone else has made (such as sprintf)

JavaScript 默认没有字符串格式化功能,尽管您可以创建自己的或使用其他人制作的功能(例如sprintf

回答by Tomá? Divi?

Looking for an answer for the same question, I just found this: https://github.com/davidchambers/string-format, which is "JavaScript string formatting inspired by Python's str.format()". It seem it's pretty much the same as python's format()function.

寻找同一问题的答案,我刚刚找到了这个:https: //github.com/davidchambers/string-format,这是“受 Python 启发的 JavaScript 字符串格式str.format()”。看起来和python的format()功能差不多。

回答by James Porter

This code allows you to specify exactly which brackets to replace with which strings. The brackets don't need to be in the same order as the arguments, and multiple brackets are possible. The format function takes an array of values as its parameter, with each key being one of the bracketed 'variables' which is replaced by its corresponding value.

此代码允许您准确指定用哪些字符串替换哪些括号。括号不需要与参数的顺序相同,并且可以使用多个括号。format 函数将一组值作为其参数,每个键都是括号中的“变量”之一,由其相应的值替换。

String.prototype.format = function (arguments) {
    var this_string = '';
    for (var char_pos = 0; char_pos < this.length; char_pos++) {
        this_string = this_string + this[char_pos];
    }

    for (var key in arguments) {
        var string_key = '{' + key + '}'
        this_string = this_string.replace(new RegExp(string_key, 'g'), arguments[key]);
    }
    return this_string;
};

'The time is {time} and today is {day}, {day}, {day}. Oh, and did I mention that the time is {time}.'.format({day:'Monday',time:'2:13'});
//'The time is 2:13 and today is Monday, Monday, Monday. Oh, and did I mention that the time is 2:13.'

回答by Riccardo Volpe

JS:

JS:

String.prototype.format = function () {
    var str = this;
    for (var i = 0; i < arguments.length; i++) {
        str = str.replace('{' + i + '}', arguments[i]);
    }
    return str;
}

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

python_format = 'The lazy {2} {1} over the {0}'.format(bar1,bar2,bar3);

document.getElementById("demo").innerHTML = "JavaScript equivalent of Python's format() function:<br><span id='python_str'>" + python_format + "</span>";

HTML:

HTML:

<p id="demo"></p>

CSS:

CSS:

span#python_str {
    color: red;
    font-style: italic;
}

OUTPUT:

输出:

JavaScript equivalent of Python's format() function:

The lazy dog jumped over the foobar

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

懒狗跳过了foobar

DEMO:

演示:

jsFiddle

js小提琴

回答by user1114907

In the file

在文件中

https://github.com/BruceSherwood/glowscript/blob/master/lib/glow/api_misc.js

https://github.com/BruceSherwood/glowscript/blob/master/lib/glow/api_misc.js

is a function String.prototype.format = function(args) that fully implements the Python string.format() function, not limited simply to handling character strings.

是一个函数 String.prototype.format = function(args) ,它完全实现了 Python string.format() 函数,不仅限于处理字符串。

回答by Yash Mehrotra

There is a way, but not exactly using format.

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

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

jsfiddle - link

jsfiddle -链接