相当于字符串。在jQuery格式

时间:2020-12-27 20:18:22

I'm trying to move some JavaScript code from MicrosoftAjax to JQuery. I use the JavaScript equivalents in MicrosoftAjax of the popular .net methods, e.g. String.format(), String.startsWith(), etc. Are there equivalents to them in jQuery?

我正在尝试将一些JavaScript代码从MicrosoftAjax迁移到JQuery。我在流行的。net方法的MicrosoftAjax使用了JavaScript的等价物,例如String.format()、String.startsWith()等等。

20 个解决方案

#1


187  

The source code for ASP.NET AJAX is available for your reference, so you can pick through it and include the parts you want to continue using into a separate JS file. Or, you can port them to jQuery.

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

Here is the format function...

这是格式函数……

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

And here are the endsWith and startsWith prototype functions...

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

#2


144  

This is a faster/simpler (and prototypical) variation of the function that Josh posted:

这是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;
};

Usage:

用法:

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

I use this so much that I aliased it to just f, but you can also use the more verbose format. e.g. 'Hello {0}!'.format(name)

我使用了这么多,以至于我把它转成了f,但是你也可以使用更详细的格式。如。“你好,{ 0 } !”.format(名字)

#3


120  

Many of the above functions (except Julian Jelfs's) contain the following error:

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

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

Or, for the variants that count backwards from the end of the argument list:

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

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

Here's a correct function. It's a prototypal variant of Julian Jelfs's code, which I made a bit tighter:

这是一个正确的函数。这是Julian Jelfs代码的原型变体,我把它写得更严密了:

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

And here is a slightly more advanced version of the same, which allows you to escape braces by doubling them:

这里有一个稍微高级一点的版本,你可以通过加倍来摆脱括号:

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

This works correctly:

这是正确的:

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

Here is another good implementation by Blair Mitchelmore, with a bunch of nice extra features: https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format

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

#4


46  

Made a format function that takes either a collection or an array as arguments

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

Usage:

用法:

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

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

Code:

代码:

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

#5


36  

There is an (somewhat) official option: jQuery.validator.format.

有一个(有点)正式的选项:jQuery.validator.format。

Comes with jQuery Validation Plugin 1.6 (at least).
Quite similar to the String.Format found in .NET.

jQuery验证插件1.6(至少)。和弦很相似。格式在。net中找到。

Edit Fixed broken link.

编辑固定失效链接。

#6


14  

If you're using the validation plugin you can use:

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

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

jQuery.validator。格式(“{0}{1}”、“cool”、“formatting”)=“cool formatting”

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

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

#7


12  

Though not exactly what the Q was asking for, I've built one that is similar but uses named placeholders instead of numbered. I personally prefer having named arguments and just send in an object as an argument to it (more verbose, but easier to maintain).

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

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

Here's an example usage...

这里有一个例子使用……

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

#8


6  

None of the answers presented so far has no obvious optimization of using enclosure to initialize once and store regular expressions, for subsequent usages.

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

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

Also, none of the examples respects format() implementation if one already exists.

另外,如果已经存在了格式()的实现,那么这些例子都没有。

#9


4  

Here's mine:

这是我的:

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

Not bullet proof but works if you use it sensibly.

不是防弹的,但如果你合理地使用它就会起作用。

#10


4  

Using a modern browser, which supports EcmaScript 2015 (ES6), you can enjoy Template Strings. Instead of formatting, you can directly inject the variable value into it:

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

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

Note the template string has to be written using back-ticks (`).

注意,模板字符串必须使用回签(')编写。

#11


2  

Here's my version that is able to escape '{', and clean up those unassigned place holders.

这是我的版本,能够逃离“{”,并清除那些未分配的地方持有者。

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

#12


2  

The following answer is probably the most efficient but has the caveat of only being suitable for 1 to 1 mappings of arguments. This uses the fastest way of concatenating strings (similar to a stringbuilder: array of strings, joined). This is my own code. Probably needs a better separator though.

下面的答案可能是最有效的,但是有一点需要注意,它只适用于1到1个参数的映射。这使用了连接字符串的最快方式(类似于stringbuilder: string of string, join)。这是我自己的代码。也许需要更好的分隔符。

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

Use it like:

使用它:

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

#13


2  

Now you can use Template Literals:

现在可以使用模板文字:

var w = "the Word";
var num1 = 2;
var num2 = 3;

var long_multiline_string = `This is very long
multiline templete string. Putting somthing here:
${w}
I can even use expresion interpolation:
Two add three = ${num1 + num2}
or use Tagged template literals
You need to enclose string with the back-tick (\` \`)`;

console.log(long_multiline_string);

#14


1  

This violates DRY principle, but it's a concise solution:

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

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

#15


1  

Way past the late season but I've just been looking at the answers given and have my tuppence worth:

虽然赛季已经过去了,但我一直在寻找所给出的答案,我的努力是值得的:

Usage:

用法:

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

Method:

方法:

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

Result:

结果:

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

#16


0  

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

#17


0  

I couldn't get Josh Stodola's answer to work, but the following worked for me. Note the specification of prototype. (Tested on IE, FF, Chrome, and Safari.):

我找不到Josh Stodola的答案,但是下面的方法对我很有效。请注意原型的规范。(在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 really should be a clone of this so as not to be a destructive method, but it's not really necessary.

s真的应该是这个的克隆,这样就不会成为一个破坏性的方法,但这并不是真的必要。

#18


0  

Expanding on adamJLev's great answer above, here is the TypeScript version:

在上面关于adamJLev的伟大答案的扩展中,以下是打字稿版本:

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

#19


0  

I have a plunker that adds it to the string prototype: string.format It is not just as short as some of the other examples, but a lot more flexible.

我有一个柱塞将它添加到字符串原型:string。格式它不仅像其他例子一样简短,而且更灵活。

Usage is similar to c# version:

使用类似于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

Also, added support for using names & object properties

此外,还支持使用名称和对象属性。

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

#20


0  

You can also closure array with replacements like this.

您还可以使用这样的替换来关闭数组。

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

or you can try bind

或者你也可以尝试绑定。

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

#1


187  

The source code for ASP.NET AJAX is available for your reference, so you can pick through it and include the parts you want to continue using into a separate JS file. Or, you can port them to jQuery.

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

Here is the format function...

这是格式函数……

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

And here are the endsWith and startsWith prototype functions...

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

#2


144  

This is a faster/simpler (and prototypical) variation of the function that Josh posted:

这是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;
};

Usage:

用法:

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

I use this so much that I aliased it to just f, but you can also use the more verbose format. e.g. 'Hello {0}!'.format(name)

我使用了这么多,以至于我把它转成了f,但是你也可以使用更详细的格式。如。“你好,{ 0 } !”.format(名字)

#3


120  

Many of the above functions (except Julian Jelfs's) contain the following error:

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

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

Or, for the variants that count backwards from the end of the argument list:

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

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

Here's a correct function. It's a prototypal variant of Julian Jelfs's code, which I made a bit tighter:

这是一个正确的函数。这是Julian Jelfs代码的原型变体,我把它写得更严密了:

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

And here is a slightly more advanced version of the same, which allows you to escape braces by doubling them:

这里有一个稍微高级一点的版本,你可以通过加倍来摆脱括号:

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

This works correctly:

这是正确的:

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

Here is another good implementation by Blair Mitchelmore, with a bunch of nice extra features: https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format

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

#4


46  

Made a format function that takes either a collection or an array as arguments

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

Usage:

用法:

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

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

Code:

代码:

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

#5


36  

There is an (somewhat) official option: jQuery.validator.format.

有一个(有点)正式的选项:jQuery.validator.format。

Comes with jQuery Validation Plugin 1.6 (at least).
Quite similar to the String.Format found in .NET.

jQuery验证插件1.6(至少)。和弦很相似。格式在。net中找到。

Edit Fixed broken link.

编辑固定失效链接。

#6


14  

If you're using the validation plugin you can use:

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

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

jQuery.validator。格式(“{0}{1}”、“cool”、“formatting”)=“cool formatting”

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

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

#7


12  

Though not exactly what the Q was asking for, I've built one that is similar but uses named placeholders instead of numbered. I personally prefer having named arguments and just send in an object as an argument to it (more verbose, but easier to maintain).

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

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

Here's an example usage...

这里有一个例子使用……

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

#8


6  

None of the answers presented so far has no obvious optimization of using enclosure to initialize once and store regular expressions, for subsequent usages.

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

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

Also, none of the examples respects format() implementation if one already exists.

另外,如果已经存在了格式()的实现,那么这些例子都没有。

#9


4  

Here's mine:

这是我的:

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

Not bullet proof but works if you use it sensibly.

不是防弹的,但如果你合理地使用它就会起作用。

#10


4  

Using a modern browser, which supports EcmaScript 2015 (ES6), you can enjoy Template Strings. Instead of formatting, you can directly inject the variable value into it:

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

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

Note the template string has to be written using back-ticks (`).

注意,模板字符串必须使用回签(')编写。

#11


2  

Here's my version that is able to escape '{', and clean up those unassigned place holders.

这是我的版本,能够逃离“{”,并清除那些未分配的地方持有者。

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

#12


2  

The following answer is probably the most efficient but has the caveat of only being suitable for 1 to 1 mappings of arguments. This uses the fastest way of concatenating strings (similar to a stringbuilder: array of strings, joined). This is my own code. Probably needs a better separator though.

下面的答案可能是最有效的,但是有一点需要注意,它只适用于1到1个参数的映射。这使用了连接字符串的最快方式(类似于stringbuilder: string of string, join)。这是我自己的代码。也许需要更好的分隔符。

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

Use it like:

使用它:

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

#13


2  

Now you can use Template Literals:

现在可以使用模板文字:

var w = "the Word";
var num1 = 2;
var num2 = 3;

var long_multiline_string = `This is very long
multiline templete string. Putting somthing here:
${w}
I can even use expresion interpolation:
Two add three = ${num1 + num2}
or use Tagged template literals
You need to enclose string with the back-tick (\` \`)`;

console.log(long_multiline_string);

#14


1  

This violates DRY principle, but it's a concise solution:

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

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

#15


1  

Way past the late season but I've just been looking at the answers given and have my tuppence worth:

虽然赛季已经过去了,但我一直在寻找所给出的答案,我的努力是值得的:

Usage:

用法:

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

Method:

方法:

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

Result:

结果:

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

#16


0  

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

#17


0  

I couldn't get Josh Stodola's answer to work, but the following worked for me. Note the specification of prototype. (Tested on IE, FF, Chrome, and Safari.):

我找不到Josh Stodola的答案,但是下面的方法对我很有效。请注意原型的规范。(在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 really should be a clone of this so as not to be a destructive method, but it's not really necessary.

s真的应该是这个的克隆,这样就不会成为一个破坏性的方法,但这并不是真的必要。

#18


0  

Expanding on adamJLev's great answer above, here is the TypeScript version:

在上面关于adamJLev的伟大答案的扩展中,以下是打字稿版本:

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

#19


0  

I have a plunker that adds it to the string prototype: string.format It is not just as short as some of the other examples, but a lot more flexible.

我有一个柱塞将它添加到字符串原型:string。格式它不仅像其他例子一样简短,而且更灵活。

Usage is similar to c# version:

使用类似于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

Also, added support for using names & object properties

此外,还支持使用名称和对象属性。

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

#20


0  

You can also closure array with replacements like this.

您还可以使用这样的替换来关闭数组。

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

or you can try bind

或者你也可以尝试绑定。

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