Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

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');
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top