2011-10-17 94 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

我已經顯示的這個「模板字符串」示例是一個使用多行字符串的「模板字符串」。 –

相關問題