I have a website that has a translation tool. I have added a pop-up that asks the user to choose it’s language in any page the user visits.
What I’m looking for is the JS code to put on each language so when it is clicked it reloads the same page with the added or removed path.
example: www.page.com/store
When the user clicks the language French he should be redirected to: www.page.com/fr/store
If the user chooses English the URL remains www.page.com/store but if the user was in the French site, the code should remove the /fr path.
In the English link there should be two codes, reload the page if the user is in English or remove the /fr path if is in French.
Because the pop up is in every page, I cannot put just the link to the translated page, it needs to insert or delete the path to the URL.
I’m very new to JS so I’m having a lot of problems. Help would be appreciated.
<script>
function changePath() {
// Get the current URL
var currentURL = window.location.href;
// Extract the current path from the URL
var currentPath = window.location.pathname;
// Modify the path
var modifiedPath = '/fr'; //
// Concatenate the current path with the modified path
var newURL = currentURL.replace(currentPath, modifiedPath);
// Update the URL
window.location.href = newURL;
}
</script>
I have tried this but of course the whole path is removed and changed into /fr only.
2
Answers
You can pass parameter language in changePath() function and apply a condition on modified path if the path is French then go to /fr/store otherwise go to /store. In below code I pass lang as parameter and use tenary operator to check language.
I hope it will help you.
Don’t use a replace but just concatenate your values.
Also instead of the complete href. Just get the domain!