0

The task is to write a script in javaScript/jQuery(other technologies also possible) to return the domain with a .pl extension if the user language browser is set to Polish. Otherwise, the script should return .eu domain extension

I tried to use jQuery, but I cannot find an appropriate solution.

<script type="text/javascript">
        $(document).ready(function () {
   
            var userLang = navigator.language || navigator.userLanguage;
   var path = window.location.path;
   var extension = window.location.hostname;
   var ext = extension.split(".");
   var x = ext[2];
   
            if (userLang.startsWith("pl")) {
        x = "pl";
                    window.location.href = extension + x + path;
                
            else {
    x = "eu"
                    window.location.href = extension + x + path;
                }
            });
   
    </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I expect www.domain.pl/file1/files2/file3.html(it is possible to have many directories by the link) if navigator.language = "pl" else href = www.domain.eu/path

Thank you in advance for any contributions.

  • This question was asked many, many times. Possible duplicate. Check https://stackoverflow.com/questions/17680413/get-visitors-language-country-code-with-javascript-client-side – Trueman Oct 27 '19 at 22:16
  • You haven't identified what actually happens with this code or mentioned any debugging details/errors. Note you don't need the document to be ready for this either since what you are doing has nothing to do with dom elements – charlietfl Oct 27 '19 at 22:17
  • Thanks, I will take into account and remove ready attribute. The code returns syntax error in line 13. Also, I checked post specified by Trueman, but the task is to replace an extension depends on user browser language - not only read it. – Pawel Wolniak Oct 27 '19 at 22:34
  • Well no errors were mentioned. What is on line 13? A code linter can help you find syntax issues – charlietfl Oct 28 '19 at 00:14

1 Answers1

0

I found the solution, maybe will be useful for someone. Furthermore, it is possible to use the ternary operator instead of the if..else statement, to make code shorter and more readable. Enjoy - thanks for contribution. Greetings to the community.

    <script type="text/javascript">
    function myFunction(){

        var userLang = navigator.language || navigator.userLanguage;



        if (userLang.startsWith("pl")) {

                var url = window.location.toString();
                window.location = url.replace(".eu", ".pl");}

        else {

                url = window.location.toString();
                window.location = url.replace(".pl", ".eu");
            }
        };
</script>