我试图移动一些JavaScript代码从MicrosoftAjax到JQuery。我在MicrosoftAjax中使用流行的。net方法的JavaScript等等物,例如String.format(), String.startsWith()等。jQuery中是否有与之对应的函数?


当前回答

// Regex cache
_stringFormatRegex = null;
//
/// Formats values from {0} to {9}. Usage: stringFormat( 'Hello {0}', 'World' );
stringFormat = function () {
    if (!_stringFormatRegex) {
        // Initialize
        _stringFormatRegex = [];
        for (var i = 0; i < 10; i++) {
            _stringFormatRegex[i] = new RegExp("\\{" + i + "\\}", "gm");
        }
    }
    if (arguments) {
        var s = arguments[0];
        if (s) {
            var L = arguments.length;
            if (1 < L) {
                var r = _stringFormatRegex;
                for (var i = 0; i < L - 1; i++) {
                    var reg = r[i];
                    s = s.replace(reg, arguments[i + 1]);
                }
            }
        }
        return s;
    }
}

其他回答

ASP的源代码。NET AJAX可供您参考,因此您可以从中挑选并将想要继续使用的部分包含到单独的JS文件中。或者,您可以将它们移植到jQuery。

这里是格式函数…

String.format = function() {
  var s = arguments[0];
  for (var i = 0; i < arguments.length - 1; i++) {       
    var reg = new RegExp("\\{" + i + "\\}", "gm");             
    s = s.replace(reg, arguments[i + 1]);
  }

  return s;
}

这里是endsWith和startsWith的原型函数…

String.prototype.endsWith = function (suffix) {
  return (this.substr(this.length - suffix.length) === suffix);
}

String.prototype.startsWith = function(prefix) {
  return (this.substr(0, prefix.length) === prefix);
}

下面是我的版本,它能够转义'{',并清除那些未分配的占位符。

function getStringFormatPlaceHolderRegEx(placeHolderIndex) {
    return new RegExp('({)?\\{' + placeHolderIndex + '\\}(?!})', 'gm')
}

function cleanStringFormatResult(txt) {
    if (txt == null) return "";

    return txt.replace(getStringFormatPlaceHolderRegEx("\\d+"), "");
}

String.prototype.format = function () {
    var txt = this.toString();
    for (var i = 0; i < arguments.length; i++) {
        var exp = getStringFormatPlaceHolderRegEx(i);
        txt = txt.replace(exp, (arguments[i] == null ? "" : arguments[i]));
    }
    return cleanStringFormatResult(txt);
}
String.format = function () {
    var s = arguments[0];
    if (s == null) return "";

    for (var i = 0; i < arguments.length - 1; i++) {
        var reg = getStringFormatPlaceHolderRegEx(i);
        s = s.replace(reg, (arguments[i + 1] == null ? "" : arguments[i + 1]));
    }
    return cleanStringFormatResult(s);
}

下面的答案可能是最有效的,但它只适用于参数的1对1映射。这使用了连接字符串的最快方式(类似于stringbuilder:字符串数组,连接)。这是我自己的代码。可能需要一个更好的分离器。

String.format = function(str, args)
{
    var t = str.split('~');
    var sb = [t[0]];
    for(var i = 0; i < args.length; i++){
        sb.push(args[i]);
        sb.push(t[i+1]);
    }
    return sb.join("");
}

像这样使用它:

alert(String.format("<a href='~'>~</a>", ["one", "two"]));

到目前为止,所有给出的答案都没有明显的优化,即使用enclosure来初始化一次并存储正则表达式,以供后续使用。

// DBJ.ORG string.format function
// usage:   "{0} means 'zero'".format("nula") 
// returns: "nula means 'zero'"
// place holders must be in a range 0-99.
// if no argument given for the placeholder, 
// no replacement will be done, so
// "oops {99}".format("!")
// returns the input
// same placeholders will be all replaced 
// with the same argument :
// "oops {0}{0}".format("!","?")
// returns "oops !!"
//
if ("function" != typeof "".format) 
// add format() if one does not exist already
  String.prototype.format = (function() {
    var rx1 = /\{(\d|\d\d)\}/g, rx2 = /\d+/ ;
    return function() {
        var args = arguments;
        return this.replace(rx1, function($0) {
            var idx = 1 * $0.match(rx2)[0];
            return args[idx] !== undefined ? args[idx] : (args[idx] === "" ? "" : $0);
        });
    }
}());

alert("{0},{0},{{0}}!".format("{X}"));

此外,如果已经存在format()实现,那么所有示例都不尊重它。

// Regex cache
_stringFormatRegex = null;
//
/// Formats values from {0} to {9}. Usage: stringFormat( 'Hello {0}', 'World' );
stringFormat = function () {
    if (!_stringFormatRegex) {
        // Initialize
        _stringFormatRegex = [];
        for (var i = 0; i < 10; i++) {
            _stringFormatRegex[i] = new RegExp("\\{" + i + "\\}", "gm");
        }
    }
    if (arguments) {
        var s = arguments[0];
        if (s) {
            var L = arguments.length;
            if (1 < L) {
                var r = _stringFormatRegex;
                for (var i = 0; i < L - 1; i++) {
                    var reg = r[i];
                    s = s.replace(reg, arguments[i + 1]);
                }
            }
        }
        return s;
    }
}