Search code examples
javascriptjquerystringmootoolssubstitution

Is there any method like substitute of MooTools in jQuery?


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

Does jQuery has this method or similar?


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