1

I am trying to replace Umlauts in both directions. I managed to replace Umlauts in one direction. For example, a string has an ö (Björn) than oe (Bjoern) should be written. This is the code I used:

umlauts = {"ä":"ae", "ü":"ue", "ö":"oe"}

replaceUmlaute = function(s) {
return s.replace(/[äöüß]/g, function($0) {
 return umlauts[$0] })
}

How could I change the code in order to make it dynamic so the umlaut would be replaced in both ways Björn -> Bjoern or Bjoern->Björn. I need a function that takes a string and checks the umlauts. If its an ö then switch to oe and if its an oe then switch to ö. Thanks!

clde
  • 219
  • 3
  • 12
  • why can't you just add keys going in the other directions to the umlaut variable, and update your regex to match those keys? – driusan Feb 22 '16 at 15:43
  • 6
    I hope you don't have anyone named `Joe`, `Sue` or `Kae`. – Daniel A. White Feb 22 '16 at 15:45
  • @driusan I tried this but it does not seem to work. – clde Feb 22 '16 at 15:48
  • Please watch out that at least for the german language the reverse direction (i.e. "oe" => "ö" etc.) is not necessarily grammatically correct. For example "Quetschung" => "Qütschung", "kongruent" => "kongrünt" etc. – Entimon Feb 01 '21 at 16:35

1 Answers1

6

Using one function to go both ways like this:

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|ue|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;

Initially a duplicate of Replace multiple strings with multiple other strings.

In your case:

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|ue|ss/gi, function(matched){
  return mapObj1[matched];
});
document.write(str)

str = str.replace(/ä|ö|ü|ß/gi, function(matched){
  return mapObj2[matched];
});

document.write('<br/>'+str)
mplungjan
  • 169,008
  • 28
  • 173
  • 236