-1

I am trying to do a simple replace of a string.

function LanguageSwitch (lang) {
    var pathname = window.location.pathname;

    if (lang == "da") {
        pathname = pathname.replace(array("/de/", "/en/"), "/da/");
    }
    if (lang == "en") {
        pathname = pathname.replace(array("/da/", "/de/"), "/en/");
    }
    if (lang == "de") {
        pathname = pathname.replace(array("/da/", "/en/"), "/de/");
    }

    window.location.replace(pathname);
}

this does work:

function LanguageSwitch (lang) {
    var pathname = window.location.pathname;

    if (lang == "da") {
        pathname = pathname.replace("/en/", "/da/");
    }
    if (lang == "en") {
        pathname = pathname.replace("/da/", "/en/");
    }

    window.location.replace(pathname);
}

but adding a third language selector - not so much ;-)

Any ideas.

EDIT: This is not a try to replace [x,y,z] with [a,b,c] but more an replace [x,y,z] with "a"

osomanden
  • 599
  • 1
  • 10
  • 26
  • It would be better if you logged `lang` and `pathname` variables in cases when it doesn't work. – Vasili Apr 17 '17 at 10:29
  • Dude, Please put some efforts to solve problem by reffering to others answers rather posting questions. Answer to your question is already exists [Here](http://stackoverflow.com/questions/5069464/replace-multiple-strings-at-once) And [Here Too](http://stackoverflow.com/questions/15604140/replace-multiple-strings-with-multiple-other-strings) – Chirag Apr 17 '17 at 10:34
  • Possible duplicate of [Replace multiple strings at once](http://stackoverflow.com/questions/5069464/replace-multiple-strings-at-once) – Chirag Apr 17 '17 at 10:35

2 Answers2

1

Try

function LanguageSwitch (lang) {
    var pathname = window.location.pathname;

    if (lang == "da") {
        pathname = pathname.replace(/\/en\/|\/de\//, "/da/");
    }
    if (lang == "en") {
        pathname = pathname.replace(/\/da\/|\/de\//, "/en/");
    }
if (lang == "de") {
        pathname = pathname.replace(/\/da\/|\/en\//, "/de/");
    }

    window.location.replace(pathname);
}
S B
  • 1,363
  • 12
  • 21
0

var pathname = 'www.here-is-lang-da.com';
$('h1').text(pathname);
pathname = pathname.replace(/da|de/g, 'en');
$('h2').text(pathname);
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<h1></h1>
<h2></h2>
</body>
</html>
Swapnil Patil
  • 912
  • 1
  • 7
  • 14