2015-06-12 49 views
1

我有一個字符串,其變量通過replaceRegExp被替換爲指定的值。正向變量替換

如何以這種方式實現它,以避免在原始值碰巧包含變量名稱時用不同值替換注入值?

例子:

var s = format("$1, $2, $3", ["$2", "two", "three"]); 
// returns: "two, two, three", 
// needed: "$2, two, three" 

如何實現這樣的功能format,它可以讓我們避免更換碰巧在他們可識別的變量先前注入的價值觀呢?

回答

2

string.replace(callback)是最簡單的選擇:

function format(str, args) { 
 
    return str.replace(/\$(\d+)/g, function(_, idx) { 
 
    return args[idx - 1]; 
 
    }); 
 
} 
 

 
var s = format("$1, $2, $3", ["$2", "two", "three"]); 
 
document.write(s)

+0

謝謝,這個作品! –