JavaScript 实现 String format with ${}

JavaScript 实现 String format with ${}

1
2
3
4
5
6
7
8
9
function str_format(str, replacements) {
return str.replace(/\$\{\w+\}/g, function(placeholderWithDelimiters) {
var placeholderWithoutDelimiters = placeholderWithDelimiters.substring(2, placeholderWithDelimiters.length - 1);
var stringReplacement = replacements[placeholderWithoutDelimiters] || placeholderWithDelimiters;
return stringReplacement;
});
}
console.log(str_format('${name} is cat', {name: 'tom'}))
console.log(str_format('${0} is cat', ['tom']))