2017-04-17 47 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); 
} 

,但增加了第三語言選擇 - 與其說;-)

任何想法。

編輯:這不是一個嘗試以 「a」

+0

這將是更好,如果你在登錄的情況下'lang'和'pathname'變量時,這是行不通的。 –

+0

老兄,請付出一些努力,通過回答他人的問題來解決問題,而不是發佈問題。您的問題的答案已經存在[這裏](http://stackoverflow.com/questions/5069464/replace-multiple-strings-at-once) 和[This Too](http://stackoverflow.com/questions/ 15604140 /替換多個字符串與多個其他字符串) – Chirag

+0

可能重複[一次替換多個字符串](http://stackoverflow.com/questions/5069464/replace-multiple-strings-at-once) – Chirag

回答

1

嘗試

與[A,B,C],但以上的取代[X,Y,Z]來代替[X,Y,Z]
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>