Search code examples
javascripthtmlreplacehyperlinkhtml-input

Is there a way to make a button redirect to the page of the current link, but in another language


Hello I have 2 blogs in two different languages. All links are identical except the fact that the English blog has a "-en" suffix after the blog name, while the Greek blog has a "-el" suffix.

I want to place a button somewhere that uses the link of the current page. For example "https://cookwithnick-en.blogspot.com/2021/07/mini-piroshki.html", converts it to "https://cookwithnick-el.blogspot.com/2021/07/mini-piroshki.html" and opens it on the same tab.

I have managed to make the following code but doesn't work:

<input type="button" onclick="location.href=window.location.href.replace("en", "el");" value="Greek" />

And while the code works if the ".replace("en", "el");" is missing (it redirects to the exact same page) I want to convert the link to the other language.

Thank you for your time and suggestions.


Solution

  • Just replace double quotes with single quotes in .replace("en", "el") So:

    <input type="button" onclick="location.href=window.location.href.replace('en', 'el');" value="Greek" />
    

    However, it's better to do like this:

    <input type="button" id="change-lang" value="Greek" />
    
    <script>
        document.getElementById("change-lang").addEventListener("click", function(){
            location.href=window.location.href.replace('en', 'el');
        });
    </script>