Snake Eyes
Snake Eyes

Reputation: 16764

Use %s in javascript alert with C# and ASP.NET

I have an XML file which has a simple nodes like:

<question lang='en'>Do you want to buy %s from us ?</question>
<question lang='fr'>Voulez-vous acheter chez nous cette %s ?</question>

I have a library in C# (with ASP.NET) which takes node value depending by user language.

I want to use the text in javascript alert like

var test = '<%=Language.GetString(Question.EN) %>';

I want to display the following content in alert dialog by calling a similary sprintf in javascript.

Or have I to use this plugin: http://www.diveintojavascript.com/projects/javascript-sprintf ?

Thank you

Upvotes: 1

Views: 412

Answers (1)

Zeta
Zeta

Reputation: 105925

You could use String.prototype to add a new function to the String type (JSFiddle demo):

String.prototype.sprintf = function(){
    // if argument list is empty
    // return this as new string
    if(arguments.length === 0)
        return this;

    // copy all arguments except the first one
    var newArgs = [].slice.call(arguments,1);    

    // Replace %d, %s, %f, %l, %u with first argument
    var tempString = this.replace(/%[dsflu]/,arguments[0]);

    // call again until all arguments are used
    return tempString.sprintf.apply(tempString,newArgs);
};

var testString = "%s! Do you want to use %s?";
document.write(testString.sprintf("Hello","String.prototype.sprintf"));

Upvotes: 2

Related Questions