我正在尝试从两个方向替换Umlauts。我设法朝一个方向替换了Umlauts。例如,字符串应带有ö(Björn),而不是oe(Bjoern)。这是我使用的代码:
umlauts = {"ä":"ae", "ü":"ue", "ö":"oe"}
replaceUmlaute = function(s) {
return s.replace(/[äöüß]/g, function($0) {
return umlauts[$0] })
}
我该如何更改代码以使其具有动态性,这样才能以Björn-> Bjoern或Bjoern->Björn的两种方式替换变音符号。
我需要一个带有字符串并检查变音符号的函数。如果它的ö则切换到oe,如果它的oe则切换到ö。谢谢!
最佳答案
使用一个功能同时进行
var str = "Bjoern, Joern, und ein Schloss am Woerthersee, Suess, Bjoern, Joern, und ein Schloss am Woerthersee, Suess";
var mapObj = {
"ae":"ä",
"oe":"ö",
"ue":"ü",
"ss":"ß",
"ä":"ae",
"ö":"oe",
"ü":"ue",
"ß":"ss"
}, reg1 = /ä|ö|ü|ß/gi, reg2 = /ae|oe|aa|ss/gi;
function conv(str) {
var reg = /ä|ö|ü|ß/i.test(str)?reg1:reg2;
return str.replace(reg, function(matched, offset, s){
return mapObj[matched];
});
}
str = conv(str);
document.body.innerHTML += '<br/>1:'+str;
str = conv(str);
document.body.innerHTML += '<br/>2:'+str;
最初与Replace multiple strings with multiple other strings重复
在您的情况下:
var str = "Bjoern, Joern, und ein Schloss am Woerthersee.";
var mapObj1 = {
"ae":"ä",
"oe":"ö",
"ue":"ü",
"ss":"ß"
};
var mapObj2 = {
"ä":"ae",
"ö":"oe",
"ü":"ue",
"ß":"ss"
};
str = str.replace(/ae|oe|aa|ss/gi, function(matched){
return mapObj1[matched];
});
document.write(str)
str = str.replace(/ä|ö|ü|ß/gi, function(matched){
return mapObj2[matched];
});
document.write('<br/>'+str)
关于javascript - 双向更换Umlauts,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35557785/