2011-10-17 54 views

回答

32

如果你想有类似的东西,你可以创建一个功能:

function parse(str) { 
    var args = [].slice.call(arguments, 1), 
     i = 0; 

    return str.replace(/%s/g, function() { 
     return args[i++]; 
    }); 
} 

用法:

s = parse('hello %s, how are you doing', my_name); 

这仅仅是一个简单的例子,并没有考虑到不同nt种数据类型(如%i等)或转义%s。但我希望如果给你一些想法。我很确定也有库提供这样的功能。

+1

这基本上是你得到的最好的结果,因为它不在Python中直接支持。 –

+0

另一个答案,功能util.format(),应该是被接受的答案...虽然最好它也会提到ES6的模板字符串(这在2011年不存在)。 我们真的应该能够维基劫持旧问题,以保持更新。 :\ –

+0

@KyleBaker:有足够的代表你可以编辑答案;) –

14

做那

s = 'hello ' + my_name + ', how are you doing' 
+2

所以...这是不可能的? – TIMEX

+0

你是什么意思“它不可能”? :?如果您想要格式化文本,您可以按照Felix Kling的描述进行操作。这是我在这里看到的最好的答案;):) –

+0

@TIMEX可能只是试一试。 –

2
var user = "your name"; 
var s = 'hello ' + user + ', how are you doing'; 
4

一些方法来扩展String.prototype,或者使用ES2015 template literals

var result = document.querySelector('#result'); 
 
// ----------------------------------------------------------------------------------- 
 
// Classic 
 
String.prototype.format = String.prototype.format || 
 
    function() { 
 
    var args = Array.prototype.slice.call(arguments); 
 
    var replacer = function (a){return args[a.substr(1)-1];}; 
 
    return this.replace(/(\$\d+)/gm, replacer) 
 
}; 
 
result.textContent = 
 
    'hello $1, $2'.format('[world]', '[how are you?]'); 
 

 
// ES2015#1 
 
'use strict' 
 
String.prototype.format2 = String.prototype.format2 || 
 
    function(...merge) { return this.replace(/\$\d+/g, r => merge[r.slice(1)-1]); }; 
 
result.textContent += '\nHi there $1, $2'.format2('[sir]', '[I\'m fine, thnx]'); 
 

 
// ES2015#2: template literal 
 
var merge = ['[good]', '[know]']; 
 
result.textContent += `\nOk, ${merge[0]} to ${merge[1]}`;
<pre id="result"></pre>

2

如果您正在使用的node.js,console.log()采用格式字符串作为第一个参数:

console.log('count: %d', count); 
+0

这是一个好点,但问题是关于字符串插值。 'console.log()'只输出格式化的字符串到'STDOUT'。换句话说,你不能使用'count:%d'的结果 –

+3

'var result = util.format('count:%d',count);' –

34

util.format做到这一点。

这将是v0.5.3一部分,可以这样使用:

var uri = util.format('http%s://%s%s', 
     (useSSL?'s':''), apiBase, path||'/'); 
+3

不错,谢谢你的提示! console.log('%s',value)也应该有效。 – Azat

168

随着Node.js的v4,您可以使用ES6的Template strings

var my_name = 'John'; 
var s = `hello ${my_name}, how are you doing`; 
console.log(s); // prints hello John, how are you doing 

你需要反引号`内包串 而不是'

+7

这应该是IMO的标记答案。 –

+0

加1因为我们在2017年,ES6基本上是节点世界的标准。 – Jankapunkt

+0

这是(2017)正确的答案。请注意,您需要在工具链中使用Babel来支持旧版浏览器。 – superluminary

23

node.js>4.0它与ES6标准更加兼容,其中字符串操作大大改进。

var s = `hello ${my_name}, how are you doing`; 
// note: tilt ` instead of single quote ' 

凡字符串可以传播多条线路,它使模板或HTML/XML的过程很简单:作为

答案原来的问题可以很简单。关于它的更多细节和更多功能:Template literals are string literals at mozilla.org。

+2

“倾斜'而不是单引号'”你可以节省可能日:) :) –

+0

已经有一个这样的答案:thinking_face: –

1

const format = (...args) => args.shift().replace(/%([jsd])/g, x => x === '%j' ? JSON.stringify(args.shift()) : args.shift()) 
 

 
const name = 'Csaba' 
 
const formatted = format('Hi %s, today is %s and your data is %j', name, Date(), {data: {country: 'Hungary', city: 'Budapest'}}) 
 

 
console.log(formatted)

-1

以下是在一个节点多行字符串文字例子。JS。

> let name = 'Fred' 
> tm = `Dear ${name}, 
... This is to inform you, ${name}, that you are 
... IN VIOLATION of Penal Code 64.302-4. 
... Surrender yourself IMMEDIATELY! 
... THIS MEANS YOU, ${name}!!! 
... 
... ` 
'Dear Fred,\nThis is to inform you, Fred, that you are\nIN VIOLATION of Penal Code 64.302-4.\nSurrender yourself IMMEDIATELY!\nTHIS MEANS YOU, Fred!!!\n\n' 
console.log(tm) 
Dear Fred, 
This is to inform you, Fred, that you are 
IN VIOLATION of Penal Code 64.302-4. 
Surrender yourself IMMEDIATELY! 
THIS MEANS YOU, Fred!!! 


undefined 
> 
+0

它被称为*模板字符串*,你可能只想upvote [这个现有的答案](https://stackoverflow.com/a/32695337/1048572) – Bergi

+0

我已经显示的这个“模板字符串”示例是一个使用多行字符串的“模板字符串”。 –

相关问题