adjust the placement of the divided windows as needed

My goal is to dynamically redirect users based on their language choice selected from a dropdown menu, while retaining their current website location.

For example:

  1. If the user visits xxxx.com, they should be redirected to xxxx.com/langchoice.
  2. If the user is on xxxx.com/currentlang/test.php, they should be directed to xxxx.com/langchoice/test.php.
  3. If the user accesses xxxx.com/test.php, they should be taken to xxxx.com/langchoice/test.php.

I have already implemented solutions for scenarios 1 and 2. However, I am not entirely satisfied with my current code, as it requires manual modification every time a new language needs to be added. Is there a more efficient way to achieve this?

var currentLocation = window.location.href;

if (currentLocation.indexOf(".php") != -1) 
{
    if (currentLocation.indexOf("/en/") != -1)
    {
        var newLocation = window.location.href.replace("/en/", "/"+evt.selectedItem+"/");
    }
    else if (currentLocation.indexOf("/gr/") != -1)
    {
        var newLocation = window.location.href.replace("/gr/", "/"+evt.selectedItem+"/");
    }
    else if (currentLocation.indexOf("/it/") != -1)
    {
        var newLocation = window.location.href.replace("/it/", "/"+evt.selectedItem+"/");
    }
    window.location.replace(newLocation); 
}
else
{
    var newLocation = window.location.href.replace("#", "") + evt.selectedItem;
    window.location.replace(newLocation); 
}

Answer №1

Checking for the presence of a "language" is essential, and here is one way to go about replacing it:

There are numerous methods to accomplish this task; however, I will outline just one.

let originalPath = window.location.pathname;
let newPath = originalPath.replace(/^\/[^\/]*/, "/" + selectedItem);
let updatedUrl = window.location.href.replace(originalPath, newPath);

To perform the detection, a straightforward test can be done:

let hasLanguage = (/^\/(en|fr|es)\//i).test(window.location.pathname);

The challenge lies in maintaining an up-to-date language list.

Answer №2

Is storing langchoice in a cookie the best way to maintain persistence? Or is there another method that would be more effective?

It seems like you're suggesting that the user should always be directed to:

xxxx.com/[langchoice]etc

If this is the case, perhaps one approach could be to split the URL by '/', then check if [1] matches the value stored in the langchoice cookie. If it doesn't match, consider replacing it with the correct value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The jsonData fails to display on the console without any errors, it simply refuses to print

.controller('StocksCtrl',['$scope','$stateParams','$http', function($scope, $stateParams) { //Retrieving stock data from Yahoo Finance API $http.get("http://finance.yahoo.com/webservice/v1/symbols/YHOO/quo ...

Managing the display of an extensive list of items in react - best practices

I'm facing a challenge with performance as I have a significant number of items to render and the data is constantly being updated in real-time via socket-io. How can I optimize for performance when the table of items is being rendered frequently due ...

Using a custom jQuery function within an Angular component class

I have a custom query function that I wrote in a JavaScript file located under the source folder (/src/assets/inlineedit.js) of my Angular application. Here is the content of the file: $.fn.inlineEdit = function(replaceWith, connectWith) { $(this).ho ...

The purpose of eventOverlap is to enable the inclusion of another event with a distinct tag within the same day

Here is the code snippet: eventOverlap: function(stillEvent, movingEvent) { console.log("I am overlapping something"); if (stillEvent.tags == ""|| movingEvent.tags == "") { console.log("One of the events h ...

Convert to a TypeScript map

Here are the configurations I am working with: type Choice = { value: any, label: any } Additionally, there is a role interface: export interface UserRole { id: number name: string } I have a set of roles: const userRoles:UserRole[]:[ {id:1,name: ...

Error: excessive recursion detected in <div ng-view="" class="ng-scope">

I've recently started learning angularJS and I've encountered an error that I need help with. Below is my index.html file: <body ng-app="myApp"> <div ng-view></div> <a href="table">click</a> <script ...

Is there a way to automatically fill number fields by clicking on radio buttons using a JavaScript function?

Currently, I am facing an issue with a task that involves three elements: 1. Two Number fields (from standard class) that need to be populated dynamically. 2. A Javascript function designed to extract coordinates using geolocator. 3. A radio button which, ...

Error: Unable to Navigate to Present Location ("/search") as It is Duplicated

I keep encountering the error message NavigationDuplicated when I attempt to perform multiple searches. My search function is located in the navbar, and it's configured to capture the input value using a model. Subsequently, this value is passed as a ...

Use the jQuery function `stop(true, true)` to swiftly end all animations currently in the queue

For handling animations in jQuery, I have been utilizing the stop(true, true) method to clear running animations so that the next one can start right away. What I observed was that while the first parameter, clearQueue, clears the entire animation queue, t ...

Attempting to transmit JavaScript information to my NodeJS server

Having some trouble sending geolocation data to NodeJS through a POST request. When I check the console log in my NodeJS code, it's just showing an empty object. I've already tested it with postman and had no issues receiving the data. The probl ...

jQuery Show/Hide Not Working Properly

I'm attempting to showcase one Tweet at a time and have it rotate through different tweets. I'm facing an issue where it works correctly on one type of page, but not on the other. Could this be due to a CSS precedence rule overriding the function ...

Create a new object variable within an Angular2 or JavaScript application

Having experience with Angular 1, I used to organize my variables like this: var options = {}; options.location = "test"; options.time = "today"; Transitioning to Angular 2, I want to continue with the same practice of grouping variables by adding them t ...

Utilizing React Higher Order Components with called functions: "You cannot render functions as a React child"

Please refer to this codesandbox. I am currently working on creating a react Higher Order Component (HOC) that takes in both a functional component and a function to be executed within the HOC. In order to do this, I understand that I need to develop a re ...

Issues with CreateJS chained animations failing to reach their intended target positions

Currently, I am tackling a project that involves using Three.js and CreateJS. However, I have encountered an issue with the animations when trying to move the same object multiple times. The initial animation fails to reach the target position, causing sub ...

What is the best way to cancel an upload file to the server and delete the file (before the upload is completed) when utilizing AJAX post requests for file uploads?

Is there a way to cancel an upload file to the server and delete the file if the upload is not finished, when using AJAX post requests for uploading files? Here is my AJAX upload code: $.ajax({ url: 'example.php', dataType: 'text&a ...

Troubleshooting npm start error: "Cannot find module: Error: Unable to resolve..." when relocating webpack/react files

Initially, my project was functioning perfectly and I could easily access my web page on localhost:8080 using Chrome. In an attempt to learn something new, I organized all my files into a folder named 'dir copy' instead of just 'dir'. O ...

Automatically trigger a Bootstrap 5.2 modal when the page loads

Currently, I've been utilizing Bootstrap in conjunction with JQuery and have a specific code snippet that displays a Modal when a page is loaded. However, with the latest version 5.2 of Bootstrap, there is a push to move away from using JQuery (which ...

Fading a hidden field in and out using JQuery when a selection is changed

Looking for a solution to toggle the visibility of a field based on selected content using jQuery? Check out this code snippet: $('#State').on('change', function() { var s = $('#State option:selected').text; if(s !== "") { ...

Use Q.js's Q.all() method when dealing with an array of promises of unknown length

I am looking to retrieve an array of promises using Q.all(); such as the code snippet below: return Q.all([ list[0].getCssValue('height'), list[1].getCssValue('height'), ..., lis ...

Is it possible to use JQgrid to navigate to a new page upon double-clicking?

I have a straightforward jQgrid implementation on my website <div id="catalogueSearchList" class="dataGrid"> <script type="text/javascript"> var catalogueSearchListConfig = { ...