views:

89

answers:

2

this is mootools code:

var myString = "{subject} is {property_1} and {property_2}.";
var myObject = {subject: 'Jack Bauer', property_1: 'our lord', property_2: 'savior'};
myString.substitute(myObject);

and does jquery has this mothod? or like this method ?

A: 

No, but there's nothing preventing you from adding it yourself:

jQuery.substitute = function(str, sub) {
    return str.replace(/\{(.+?)\}/g, function($0, $1) {
        return $1 in sub ? sub[$1] : $0;
    });
};

// usage:
jQuery.substitute('{foo}', {foo:'123'});
J-P
"$1 in sub" is a error
zjm1126
Works for me... What error is being thrown?
J-P
oh,sorry ,my wrong ,that's good~
zjm1126
A: 

There are some plugins that share a similar syntax to the String.Format method in .NET.

This one leverages the jQuery Validate plugin (commonly found on CDNs).

Example:

$("button").click(function () {
  var str = "Hello {0}, this is {1}";

  str = jQuery.validator.format(str, "World", "Bob");
  alert("'" + str + "'");
});

The second plugin is named .NET Style String Format.

Example:

var result = $.format("Hello, {0}", "world");

These may not be exactly what you're looking for, but they may be useful.

Doc Hoffiday