3

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.

Community
  • 1
  • 1
Ayhan
  • 183
  • 1
  • 3
  • 15

1 Answers1

1

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"
VisioN
  • 143,310
  • 32
  • 282
  • 281