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

发布于 2024-08-29 05:52:01 字数 254 浏览 5 评论 0原文

这是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有这个方法或类似的方法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

萌吟 2024-09-05 05:52:01

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

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

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'});
寂寞花火° 2024-09-05 05:52:01

试试这个插件 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} ,简单而强大。

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.

笑看君怀她人 2024-09-05 05:52:01

$.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);
        }

    });
};

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

    });
};
余生再见 2024-09-05 05:52:01

有一些插件与 .NET 中的 String.Format 方法共享类似的语法。

这个利用了 jQuery Validate 插件(常见于 CDN)。

示例:

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

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

第二个插件名为 .NET 样式字符串格式

示例:

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

这些可能并不完全是您正在寻找的内容,但它们可能很有用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文