我有一个这样的对象:
myDataObject = {
name : 'Nikola Tesla',
birth : ['10 July 1856','10. Juli 1856'],
nation : ['Serbian','Serbisch'],
knownFor : ['Alternating current',' Zweiphasenwechselstrom']
}
还有两个这样的字符串模式:
var englishStr = '#name#, born #birth[1]# , #nation[1]# best known for his contributions to #knownFor[1]#';
var deutschStr = '#name#, geboren #birth[2]#, #nation[2]# Erfinder, der für seine Beiträge zur #knownFor[2]# bekannt';
现在,我想替换标记为
#properties#
的代码。如果没有像[1]或[2] smth这样的多语言指示器,我可以轻松地做到。与此类似:
$.each(myDataObject , function(n, v){
englishStr = englishStr.replace('#'+ n +'#' , v )
});
那么,我该如何处理
#prop[i]#
?谢谢 最佳答案
一种方法是从字符串到数据对象,而不是遍历所有键。
var myDataObject = {
name : 'Nikola Tesla',
birth : ['10 July 1856','10. Juli 1856'],
nation : ['Serbian','Serbisch'],
knownFor : ['Alternating current',' Zweiphasenwechselstrom']
};
var englishStr = "#name#, born #birth[1]# , #nation[1]# best known for his contributions to #knownFor[1]#";
var re = /#([^\[#]+)\[?(\d+)?\]?#/; //Looks for #STRING# or #STRING[NUMBER]#
var test;
while ( (test=re.exec(englishStr))!==null) { //Keep looking for matches in the string
var key = test[1]; //get the key to the object
var index = test[2]; //get the index if there
var item = myDataObject[key]; //get reference to the item in the object
if (index!==undefined && item) { //if we have an index, look up the value from array
index = parseInt(index,10)-1; //arrays are zero index, so need to subtract one
item = item[index]; //get the string
}
englishStr = englishStr.replace(re, item || "N/A"); //make the replacement in the string with the data from the object
};