문제

I'm not good at JS so I've been toying around with some Greasemonkey scripts I've managed to find, but they didn't perform as expected. What I want is very basic:

Check if the URL within a domain contains the variable lang - either ?lang or &lang

If the URL contains that variable, check its value: If the value is en do nothing, if however the value is anything else, replace it with en

If the URL doesn't contain the variable lang add it to the end of the URL, as in &lang=en

Any ideas?

도움이 되었습니까?

해결책

try {
    var url = document.location.toString();
    var updateUrl = updateQueryStringParameter(url, 'lang', 'en');
    console.log(updateUrl);
    console.log(url != updateUrl);
    if (url != updateUrl) {
        document.location = updateUrl;
    }
} catch (e) {}

function updateQueryStringParameter(uri, key, value) {
    var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";
    if (uri.match(re)) {
        return uri.replace(re, '$1' + key + "=" + value + '$2');
    } else {
        return uri + separator + key + "=" + value;
    }
}

다른 팁

You want to use window.location. .search contains the query in a string.

// if the query doesn't contain lang=en
if (!window.location.search.match(/[?&]lang=en(&|$)/)) {
  // either replace an existing lang=... param or append it
  window.location.search = window.location.search.
    replace(/[?&]lang=[^&]*|$/, '&lang=en');
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top