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.

5
  • Write your own printf in JS and share it with the community :-) Commented Jan 29, 2013 at 10:49
  • Why not simply use replace ? Commented Jan 29, 2013 at 10:49
  • I think replace is the best choice here. In any case your own printf in principle would make use of it, so I suggest you go ahead with that ;-). Commented Jan 29, 2013 at 10:51
  • 2
    So I conclude that your actual question has nothing to do with "dictionaries"? Commented Jan 29, 2013 at 10:53
  • duplicates: stackoverflow.com/search?q=javascript+printf Commented Jan 29, 2013 at 10:54

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.