會導致不同語言翻譯下參數順序會被改變的問題!!
因此要改寫一下原本的printf方法!!
參數命名規則: _%s<參數ID>_ , ID由1開始
參數命名範例: Hello _%s1_ !!
$.printf = function(S, PARR) {
if (!PARR) return S;
var re = /_%s[0-9]*_/g;
var matchPattern = S.match(re);//re.exec(S);
if(matchPattern != null){
var mlen = matchPattern.length;
// console.log("match len:" + mlen);
if(mlen == PARR.length){
//find str must equal to PARR
for(var i=0; i<mlen; i++) {
var pattStr = matchPattern[i];
// console.log( i + ":" + pattStr);
var pattIndex = pattStr.match(/[0-9]+/);
// console.log( i + ":" + pattIndex);
if(pattIndex > 0){
//replace parameters
S = S.replace(pattStr,PARR[pattIndex-1]);
}
}
}
}
return S;
};
範例:
var text = Hello _%s1 !! console.log($.printf(text,["ibigd"]))輸出結果: Hello ibigd !!
TIP:常用到Regex取代字串,記錄一下今天的心得!! String的match()相同於 regex物件的 exec(), 需注意正則的規則要加上g才能代表global的搜尋!!
沒有留言:
張貼留言
留個話吧:)