我有一个这样的对象:
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]这样的多语言指标,我可以轻松地做到。类似于:
$.each(myDataObject , function(n, v){
englishStr = englishStr.replace('#'+ n +'#' , v )
});
那么我可以对#prop[i]#
做些什么呢?谢谢
答案 0 :(得分:3)
一种方法是从字符串到数据对象,而不是遍历所有键。
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
};
答案 1 :(得分:1)
我建议你尝试一种稍微不同的方法。不是盲目地尝试替换值myDataObject
,而是首先提取需要替换的值,然后用它们的值替换它们。
var regex = /#(.*?)(?:\[(\d*)])?#/g;
while(match = regex.exec(englishStr)){
var matchStr = match[0];
var data = myDataObject[match[1]];
if(match[2] !== undefined){
data = data[match[2] - 1];
}
englishStr = englishStr.replace(matchStr, data);
}
答案 2 :(得分:1)
看看这可能会有所帮助
$.each(myDataObject , function(n, v){
if(typeof v == 'object'){
$.each(v , function(index, value){
englishStr = englishStr.replace('#'+ n +'[' + index + ']' + '#' , v[index-1] );
});
}
englishStr = englishStr.replace('#'+ n +'#' , v )
});
答案 3 :(得分:1)
可能有更好的解决方案,但我会做这样的事情:
myDataObject = {
name: 'Nikola Tesla',
birth: ['10 July 1856', '10. Juli 1856'],
nation: ['Serbian', 'Serbisch'],
knownFor: ['Alternating current', ' Zweiphasenwechselstrom']
};
// English: 0, Deutsch: 1
var language = 0;
var str = "#name#, born #$birth# , #$nation# best known for his contributions to #$knownFor#";
$.each(myDataObject, function (n, v) {
str = str.replace('#' + n + '#', v);
str = str.replace('#$' + n + '#', v[language]);
});
alert(str);
答案 4 :(得分:1)
您还可以将正则表达式替换中的捕获组传递给回调函数:
(请注意,如果翻译字符串中的数组是从1
编入索引的,则必须将其添加到$2
)
englishStr.replace(/#(.+?)(?:\[(\d+)\])?#/g, function($0, $1, $2){
return $2 === undefined ? myDataObject[$1] : myDataObject[$1][$2];
});