2009-06-24 360 views
182

我試圖將一些JavaScript代碼從MicrosoftAjax移動到JQuery。我在流行的.net方法的MicrosoftAjax中使用了JavaScript等價物,例如String.format(),String.startsWith()等。在jQuery中它們是否等同於它們?jQuery中String.format的等效

+1

參見http:// stack overflow.com/questions/610406/javascript-equivalent-to-printf-string-format – John 2011-08-26 12:26:30

回答

185

source code for ASP.NET AJAX is available供您參考,因此您可以選擇它並將您想要繼續使用的部分包含在單獨的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); 
} 
+2

看起來不太像它。顯然,JavaScript版本並不具備所有的花式數字格式。 http://blog.stevex.net/index.php/string-formatting-in-csharp/ – Nosredna 2009-06-24 15:09:42

+0

我可以看到他們將如何有用。特別是如果你習慣了擁有它們。 – Nosredna 2009-06-24 15:18:50

+0

哇,我實際上已經考慮過這個,但也認爲這是不可能的,因爲許可證,不知道他們在微軟許可許可下發布它,非常感謝這個 – 2009-06-25 07:00:01

36

有一個(有點)官方選項:jQuery.validator.format

附帶jQuery驗證插件1.6(至少)。
非常類似於在.NET中找到的String.Format

編輯修復了斷開的鏈接。

142

這是喬希發佈功能的更快/更簡單的(和原型)的變化:

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 ,但您也可以使用更詳細的format。例如'Hello {0}!'.format(name)

+0

隨着現代瀏覽器,有更簡單的方法:https://stackoverflow.com/a/41052964/120296 – david 2017-11-23 19:38:13

4

這裏是我的:

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

不防彈,但如果你明智使用它的作品。

0

我無法讓Josh Stodola的工作答案,但以下工作適合我。請注意規格prototype。 (測試IE,FF,鉻和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真應了克隆this以免成爲破壞性的方法,但它是不是真的有必要。

120

上述許多功能(除了朱利安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 

這裏的一個正確的功能。這是朱利安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 

這是布萊爾Mitchelmore另一個很好的實施,帶着一幫不錯的額外功能:https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format

2

這是我的版本,它能夠逃脫'{',並清理那些未分配的佔位符。

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

做了一個格式化功能是它可以是一個集合或數組作爲參數

用法:

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

雖然不正是使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' })); 
6

無有使用外殼來初始化一次,並存儲正則表達式,爲後續的用法沒有明顯的優化。

// 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()實現。

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

以下的答案可能是最有效的,但有隻告誡適合於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"])); 
0

擴展在adamJLev的偉大答案above,這裏是打字稿版本:

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

這違背了DRY原則,但它是一個簡潔的解決方案:

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

我有一個將其添加到字符串原型中的運動員: 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 
0

你也可以關閉陣列,這樣的替代支持。

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

現在你可以使用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);

4

使用新版瀏覽器,它支持的EcmaScript 2015年(ES6) ,你可以享受Template Strings。您可以直接將變量值注入其中:

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

注意模板字符串必須使用反碼(`)寫入。

0

路過去賽季末,但我剛纔一直在看給出的答案和我有兩便士的價值:

用法:

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