const defaultLanguage = availableLocales[0] let language = (window.navigator.language) const urlParams = new URLSearchParams(window.location.search) const langFromUrl = urlParams.get('lang') if (langFromUrl && availableLocales.includes(langFromUrl)) {language = langFromUrl} let pageLanguage = defaultLanguage if (availableLocales.includes(language)) {pageLanguage = language} const elements = document.querySelectorAll('[data-i18n]') const json = locales[pageLanguage] elements.forEach((element) => { const key = element.getAttribute('data-i18n') let text = key.split('.').reduce((obj, i) => (obj ? obj[i] : null), json) const variables = text.match(/{(.*?)}/g) if (variables) { variables.forEach((variable) => { Object.entries(element.dataset).filter(([key, value]) => { if (`{${key}}` === variable) { try {text = text.replace(`${variable}`, new Function(`return (${value})`)())} catch (error) {text = text.replace(`${variable}`, value)} } }) }) } element.innerHTML = text }) const htmlElement = document.querySelector('html') htmlElement.setAttribute('lang', pageLanguage)