jquery用string替换数组中的元素

时间:2017-04-17 10:26:53

标签: jquery arrays replace

我正在尝试简单地替换字符串。

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,b,c]替换[x,y,z],而是用“a”替换[x,y,z]

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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>