skip to Main Content

I wanted to set automatic links with tags and I wonder how to make it happen so I don’t have to write every case for the site.

I have Polish and English versions of the same site, but I have a problem with the web address.
For example I have sites like this:
https://example.com/tech/privacy-policy – Polish one
and
https://example.com/tech/en/privacy-policy – English one

How to make it to separate the web address into string and if it is on the Polish site to embed “en” between tech/…/privacy-policy, and how to delete it when I’m on English one?
I know that $_SERVER[‘REQUEST_URI’]; shows me web address in PHP but I don’t know how manipulate it in this certain way.

Is it possible to search for “/tech/” for futher web adresses like https:/example.com/tech/en/privacy-policy/something to search for this word and delete “en” if it’s English site redirecting to Polish one and add one if it’s the opposite side?

2

Answers


  1. You can use includes method of Javascript:

    function changeSiteLanguage() {
        var url = window.location.href;
    
        if (url.includes("/tech/en/")) {
            url = url.replace("/tech/en/", "/tech/")
        } else if (url.includes("/tech/")) {
            url = url.replace("/tech/", "/tech/en/")
        }
    
        // reload window with new URL 
        window.location.assign(url)
    }
    

    Test Cases:

    var url1 = "https://example.com/tech/en/privacy-policy";
    
    if (url1.includes("/tech/en/")) {
        url1 = url1.replace("/tech/en/", "/tech/")
    } else if (url1.includes("/tech/")) {
        url1 = url1.replace("/tech/", "/tech/en/")
    }
    
    console.log(url1)
    
    var url2 = "https://example.com/tech/privacy-policy";
    
    if (url2.includes("/tech/en/")) {
        url2 = url2.replace("/tech/en/", "/tech/")
    } else if (url2.includes("/tech/")) {
        url2 = url2.replace("/tech/", "/tech/en/")
    }
    
    console.log(url2)
    Login or Signup to reply.
  2. Here’s a way to do it using javascript:

    var url = document.createElement('a');
    url.href = 'https://example.com/tech/en/privacy-policy';
    var pathArray = url.pathname.split("/");
    var newPathPolish = "";
    var newPathEnglish = "";
    
    function checkPath(urlPath) {
    	return urlPath === "tech";
    }
    
    //Add en in the path if it doesn't exist
    if (!pathArray.includes("en")) {
    	indexAfter = pathArray.findIndex(checkPath) + 1;
    	pathArray.splice(indexAfter, 0, "en");
    }
    
    //Loop through the path creating the new paths
    for (var i = 0; i < pathArray.length; i = i + 1)
    {
    	if (pathArray[i] !== "en") {
    	  newPathPolish += pathArray[i] + '/';
    	} 
    	newPathEnglish += pathArray[i] + '/';
    }
    console.log("Polish version: " + url.origin + newPathPolish);
    console.log("English version: " + url.origin + newPathEnglish);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search