Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

marked as duplicate by Bergi, Yoshi, Kuf, ithcy, Luke Girvin Jan 29 '13 at 14:26

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
Write your own printf in JS and share it with the community :-) –  techfoobar Jan 29 '13 at 10:49
    
Why not simply use replace ? –  dystroy Jan 29 '13 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 ;-). –  Masiar Jan 29 '13 at 10:51
2  
So I conclude that your actual question has nothing to do with "dictionaries"? –  Bergi Jan 29 '13 at 10:53
    
duplicates: stackoverflow.com/search?q=javascript+printf –  Bergi Jan 29 '13 at 10:54

1 Answer 1

up vote 1 down vote accepted

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"
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.