是否有类似jQuery中MooTools的替代方法?

问题描述 投票:2回答:4

这是MooTools代码:

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

jQuery是否具有此方法或类似方法?

javascript jquery string mootools substitution
4个回答
11
投票

否,但是没有什么可以阻止您自己添加它:

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

1
投票

尝试使用此插件https://github.com/trix/nano,源代码只有几行

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

您可以使用点符号{user.name},简单而强大。


1
投票

[$.nano答案让我陷入了循环,因为如果模板点表示法中有任何错字,它会出错,而且它不允许像a['foo bar']这样的所有合法字符,因此以下是我作为$.substitute的版本插件:

/*
 * 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);
        }

    });
};

0
投票

[有些插件与.NET中的String.Format方法具有相似的语法。

[This one利用jQuery Validate插件(通常在CDN上找到)。

示例:

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

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

第二个插件名为.NET Style String Format

示例:

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

这些可能不完全是您想要的,但是它们可能有用。

© www.soinside.com 2019 - 2024. All rights reserved.