2017-04-17 69 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>