Ble*_*der 46 javascript python format
Python有这个美丽的功能来解决这个问题:
bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'
foo = 'The lazy ' + bar3 + ' ' + bar2 ' over the ' + bar1
# The lazy dog jumped over the foobar
Run Code Online (Sandbox Code Playgroud)
进入:
bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'
foo = 'The lazy {} {} over the {}'.format(bar3, bar2, bar1)
# The lazy dog jumped over the foobar
Run Code Online (Sandbox Code Playgroud)
JavaScript有这样的功能吗?如果没有,我将如何创建一个遵循与Python实现相同的语法?
CMS*_*CMS 49
使用该String.prototype.replace方法的另一种方法,使用"replacer"函数作为第二个参数:
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"
Run Code Online (Sandbox Code Playgroud)
Yas*_*tra 24
有一种方法,但不完全使用格式.
var name = "John";
var age = 19;
var message = `My name is ${name} and I am ${age} years old`;
console.log(message);Run Code Online (Sandbox Code Playgroud)
jsfiddle - 链接
小智 10
寻找同一个问题的答案,我刚刚发现了这个:https://github.com/davidchambers/string-format,这是"受Python启发的JavaScript字符串格式str.format()".它似乎与python的format()功能几乎相同.
Cor*_*lex 10
foo = (a, b, c) => `The lazy ${a} ${b} over the ${c}`
Run Code Online (Sandbox Code Playgroud)
ES6 模板字符串提供的功能与pythons字符串格式非常相似。但是,在构造字符串之前,您必须了解变量:
var templateString = `The lazy ${bar3} ${bar2} over the ${bar1}`;
Run Code Online (Sandbox Code Playgroud)
Python str.format允许您在甚至不知道要插入哪个值之前就指定字符串,例如:
foo = 'The lazy {} {} over the {}'
bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'
foo.format(bar3, bar2, bar1)
Run Code Online (Sandbox Code Playgroud)
使用arrow函数,我们可以优雅地包装模板字符串以供以后使用:
foo = (a, b, c) => `The lazy ${a} ${b} over the ${c}`
bar1 = 'foobar';
bar2 = 'jumped';
bar3 = 'dog';
foo(bar3, bar2, bar1)
Run Code Online (Sandbox Code Playgroud)
当然,这也可以与常规功能一起使用,但是箭头功能使我们可以使其成为单线。这两种功能在大多数浏览器和运行时中都可用:
小智 6
您可以在 JS 中使用模板文字,
const bar1 = 'foobar'
const bar2 = 'jumped'
const bar3 = 'dog'
foo = `The lazy ${bar3} ${bar2} over the ${bar1}`
Run Code Online (Sandbox Code Playgroud)
我认为这很有帮助。
取自YAHOOs图书馆:
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;
}
Run Code Online (Sandbox Code Playgroud)
称之为:
bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'
foo = YAHOO.Tools.printf('The lazy {0} {1} over the {2}', bar3, bar2, bar1);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20037 次 |
| 最近记录: |