2015-06-12 48 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

谢谢,这个作品! –