我在给定字符串中有两次字符串 {{value}}。当我尝试 replace() 该值时,只有该值的第一个实例被替换,而不是第二个。上面的 JSFiddle 链接演示了这一点。这是“按设计工作”还是我做错了什么?有更好的选择吗?
var str = 'Spend $ {{value}} Get $ {{value}} Off';
var result = str.replace('{{value}}', '<a href="#" id="value" data-type="text" data-pk="1" data-name="Value" data-original-title="Amount" class="editable editable-click">value</a>');
最佳答案
这是带有字符串参数的 .replace()
的默认行为(出于某种原因)。提供带有全局标志的正则表达式,它将起作用:
str.replace(/{{value}}/g, ...);
此外,由于我无论如何都在写一个,这里是 Python 的 str.format
的一个简单的 JavaScript 克隆:
String.prototype.format = function() {
if (!arguments.length) {
return this;
}
var mapping;
if (typeof arguments[0] === 'object') {
mapping = arguments[0];
} else {
mapping = arguments;
}
return this.replace(/\{(.*?)\}/g, function(match, name) {
return mapping[name];
});
};
你可以这样使用它:
str.format({value: '<a href=...'});
或者喜欢:
'{0}{1}{0}'.format(1, 2); // "121"
关于JavaScript replace() 似乎只捕获了第一击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17075410/