2017-04-17 18 views
-1

文字列を単純に置き換えようとしています。jqueryは配列の要素を文字列で置き換えます。

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); 
} 

これが行う作業:

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); 
} 

が、第三言語セレクタを追加 -

任意のアイデア;-)そんなにありません。

EDIT:これは、交換しようとする[X、Y、Z] [A、B、C]とではなく、より置き換える[X、Y、Z] ""

+0

それが動作しないときは、場合によっては、 'lang'と' pathname'変数をログインした場合には良いだろう。 –

+0

おい、質問を投稿する代わりに他の人に答えて問題を解決する努力をしてください。あなたの質問への回答はすでに存在しています[Here](http://stackoverflow.com/questions/5069464/replace-multiple-strings-at-once) [Here Too](http://stackoverflow.com/questions/ 15604140/replace-multiple-strings-multiple-other-strings) – Chirag

+0

[複数の文字列を一度に置換]の可能な複製(http://stackoverflow.com/questions/5069464/replace-multiple-strings-at-once) – Chirag

答えて

1

を試します
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); 
} 
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>

関連する問題