Possible Duplicate:
JavaScript equivalent to printf/string.format
I'm using dictionary to hold all text used in the website like
var dict = {
"text1": "this is my text"
};
Calling texts with javascript(jQuery),
$("#firstp").html(dict.text1);
And come up with a problem that some of my text is not static. I need to write some parameter into my text.
You have 100 messages
$("#firstp").html(dict.sometext+ messagecount + dict.sometext);
and this is noobish
I want something like
var dict = {
"text1": "you have %s messages"
};
How can I write "messagecount" in to where %s is.
Without any libraries, you may create your own easy string format function:
function format(str) {
var args = [].slice.call(arguments, 1);
return str.replace(/{(\d+)}/g, function(m, i) {
return args[i] !== undefined ? args[i] : m;
});
}
format("you have {0} messages", 10);
// >> "you have 10 messages"
Or via String object:
String.prototype.format = function() {
var args = [].slice.call(arguments);
return this.replace(/{(\d+)}/g, function(m, i) {
return args[i] !== undefined ? args[i] : m;
});
};
"you have {0} messages in {1} posts".format(10, 5);
// >> "you have 10 messages in 5 posts"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With