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


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

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

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

编辑固定破碎的链接。


这是Josh发布的函数的一个更快/更简单(和原型)的变体:

String.prototype.format = String.prototype.f = function() {
    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};

用法:

'Added {0} by {1} to your collection'.f(title, artist)
'Your balance is {0} USD'.f(77.7) 

我经常使用它,所以我把它的别名改成了f,但是你也可以使用更详细的格式。如。“你好,{0}!”.format(名字)


这是我的:

String.format = function(tokenised){
        var args = arguments;
        return tokenised.replace(/{[0-9]}/g, function(matched){
            matched = matched.replace(/[{}]/g, "");
            return args[parseInt(matched)+1];             
        });
    }

虽然不是防弹衣,但如果你使用得当,还是有用的。


我无法让乔希·斯托多拉的答案奏效,但下面的答案对我很管用。注意样机的规格。(在IE, FF, Chrome和Safari上测试):

String.prototype.format = function() {
    var s = this;
    if(t.length - 1 != args.length){
        alert("String.format(): Incorrect number of arguments");
    }
    for (var i = 0; i < arguments.length; i++) {       
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i]);
    }
    return s;
}

S应该是这个的克隆,这样就不会是破坏性的方法,但其实没必要。


上面的许多函数(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


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

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

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

用法:

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

虽然不完全是Q所要求的,但我已经构建了一个类似的,但使用命名占位符而不是编号。我个人更喜欢使用命名参数,并将对象作为参数发送给它(更冗长,但更容易维护)。

String.prototype.format = function (args) {
    var newStr = this;
    for (var key in args) {
        newStr = newStr.replace('{' + key + '}', args[key]);
    }
    return newStr;
}

下面是一个用法示例……

alert("Hello {name}".format({ name: 'World' }));

到目前为止,所有给出的答案都没有明显的优化,即使用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()实现,那么所有示例都不尊重它。


如果你正在使用验证插件,你可以使用:

jQuery.validator。Format ("{0} {1}", "cool", "formatting") = 'cool formatting'

http://docs.jquery.com/Plugins/Validation/jQuery.validator.format templateargumentargumentN……


<html>
<body>
<script type="text/javascript">
   var str="http://xyz.html?ID={0}&TId={1}&STId={2}&RId={3},14,480,3,38";
   document.write(FormatString(str));
   function FormatString(str) {
      var args = str.split(',');
      for (var i = 0; i < args.length; i++) {
         var reg = new RegExp("\\{" + i + "\\}", "");             
         args[0]=args[0].replace(reg, args [i+1]);
      }
      return args[0];
   }
</script>
</body>
</html>

下面的答案可能是最有效的,但它只适用于参数的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"]));

在上面adamJLev的精彩回答的基础上,下面是TypeScript版本:

// Extending String prototype
interface String {
    format(...params: any[]): string;
}

// Variable number of params, mimicking C# params keyword
// params type is set to any so consumer can pass number
// or string, might be a better way to constraint types to
// string and number only using generic?
String.prototype.format = function (...params: any[]) {
    var s = this,
        i = params.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), params[i]);
    }

    return s;
};

这违反了DRY原则,但这是一个简洁的解决方案:

var button = '<a href="{link}" class="btn">{text}</a>';
button = button.replace('{text}','Authorize on GitHub').replace('{link}', authorizeUrl);

我有一个活塞,将其添加到字符串原型: string.format 它不仅像其他一些例子一样简短,而且灵活得多。

用法类似于c#版本:

var str2 = "Meet you on {0}, ask for {1}";
var result2 = str2.format("Friday", "Suzy"); 
//result: Meet you on Friday, ask for Suzy
//NB: also accepts an array

另外,增加了对使用名称和对象属性的支持

var str1 = "Meet you on {day}, ask for {Person}";
var result1 = str1.format({day: "Thursday", person: "Frank"}); 
//result: Meet you on Thursday, ask for Frank

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

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

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

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


使用支持EcmaScript 2015 (ES6)的现代浏览器,您可以享受模板字符串。而不是格式化,你可以直接注入变量值:

var name = "Waleed";
var message = `Hello ${name}!`;

注意模板字符串必须使用反勾号(')来编写。


虽然赛季末已经过去了,但我一直在看给出的答案,并得到了我的两便士:

用法:

var one = strFormat('"{0}" is not {1}', 'aalert', 'defined');
var two = strFormat('{0} {0} {1} {2}', 3.14, 'a{2}bc', 'foo');

方法:

function strFormat() {
    var args = Array.prototype.slice.call(arguments, 1);
    return arguments[0].replace(/\{(\d+)\}/g, function (match, index) {
        return args[index];
    });
}

结果:

"aalert" is not defined
3.14 3.14 a{2}bc foo

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