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


当前回答

现在你可以使用模板文字了:

var w =“这个词”; Var num1 = 2; Var num2 = 3; var long_multiline_string = '这是非常长的 多行模板字符串。在这里放东西: $ {w} 我甚至可以使用表达式插值: 二加三= ${num1 + num2} 或者使用带标记的模板文字 你需要用反勾号(\ ' \ ')'把字符串括起来; console.log (long_multiline_string);

其他回答

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

创建了一个以集合或数组作为参数的格式函数

用法:

format("i can speak {language} since i was {age}",{language:'javascript',age:10});

format("i can speak {0} since i was {1}",'javascript',10});

代码:

var format = function (str, col) {
    col = typeof col === 'object' ? col : Array.prototype.slice.call(arguments, 1);

    return str.replace(/\{\{|\}\}|\{(\w+)\}/g, function (m, n) {
        if (m == "{{") { return "{"; }
        if (m == "}}") { return "}"; }
        return col[n];
    });
};

上面的许多函数(Julian Jelfs的除外)包含以下错误:

js> '{0} {0} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 3.14 afoobc foo

或者,对于从参数列表末尾开始向后计数的变量:

js> '{0} {0} {1} {2}'.format(3.14, 'a{0}bc', 'foo');
3.14 3.14 a3.14bc foo

这是一个正确的函数。这是Julian Jelfs代码的原型变体,我把它做得更紧凑:

String.prototype.format = function () {
  var args = arguments;
  return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; });
};

这里有一个稍微高级一点的版本,它允许你通过重复大括号来转义:

String.prototype.format = function () {
  var args = arguments;
  return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) {
    if (m == "{{") { return "{"; }
    if (m == "}}") { return "}"; }
    return args[n];
  });
};

这是正确的:

js> '{0} {{0}} {{{0}}} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 {0} {3.14} a{2}bc foo

下面是Blair mitchell的另一个很好的实现,它有很多不错的额外特性:https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format

有一个(有点)官方选项:jQuery.validator.format。

附带jQuery验证插件1.6(至少)。 非常类似于字符串。在. net中找到的格式。

编辑固定破碎的链接。

你也可以这样替换闭包数组。

var url = '/getElement/_/_/_'.replace(/_/g, (_ => this.ar[this.i++]).bind({ar: ["invoice", "id", 1337],i: 0}))
> '/getElement/invoice/id/1337

或者您可以尝试bind

'/getElement/_/_/_'.replace(/_/g, (function(_) {return this.ar[this.i++];}).bind({ar: ["invoice", "id", 1337],i: 0}))