Question

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 ?

Was it helpful?

Solution

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'});

OTHER TIPS

The $.nano answer threw me for a loop because it errors if you have any typos in your template dot notation, and furthermore it doesn't allow all legal characters like a['foo bar'] so below is my version as a $.substitute plugin:

/*
 * JQuery Substitute method allows for simple templating using JS Object dot notation.
 * Contribute link: https://gist.github.com/danielsokolowski/0954fc2a767f441720b9
 *
 * @param strTemplate - string contain the replacement tokens
 * @param objData   - an Object represetnting your replacmenet values
 *
 *  Example:
 * var strTemplate = 'Hello {user.name}'    
 * var strDatra = {'user': 'Daniel Sokolowski'}
 * alert($.substitute(strTemplate, objData)); // outputs 'Hello Daniel Sokolowski'
 *
 */
$.substitute = function(strTemplate, objData) {
    return strTemplate.replace(/\{([^{}]*)\}/g, function(math, subMatch1) {
        try {
            var keys = subMatch1.split(".");
            var value = objData[keys.shift()]; // return first element and update the original array
            while (keys.length !== 0) { // keep returning properties
                value = value[keys.shift()]
            }
            return String(value);
        } catch (err) { // return any errors as a string
            return String(value);
        }

    });
};

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.

Try this plugin https://github.com/trix/nano , the source is just a few lines

/* Nano Templates (Tomasz Mazur, Jacek Becela) */
(function($){
  $.nano = function(template, data) {
    return template.replace(/\{([\w\.]*)\}/g, function (str, key) {
      var keys = key.split("."), value = data[keys.shift()];
      $.each(keys, function () { value = value[this]; });
      return (value === null || value === undefined) ? "" : value;
    });
  };
})(jQuery);

You can use dot notation {user.name} , just simple and powerful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top