What is the js code for translating app based on switch?

Viewed 26

What can be the JavaScript code for translating app from one language to another for about 30 words, based on "switch"?

1 Answers

Well, it is like any other switch statement aswell, just with 30 cases. It should look something like this:

function translateWord(word) {
  let result = '';
  
  switch (word.toLowerCase()) {
    case 'apfel': result = 'apple'; break;
    case 'kette': result = 'chain'; break;
    case 'pflanze': result = 'plant'; break;
  }
  
  return result;
  
}

document.getElementById('result').textContent = translateWord('Apfel');
<h1 id="result"></h1>

the function "translateWord" takes a word, in this case 'Apfel' (german word for apple). That word is passed to the switch statement and transformed to lowercase so it is not case sensitive. After the result is returned and put into the <h1>-Tags on the html page.

Now if you just want to translate 30 words, this might be an option, but common dicionaries have well over six digits of words. So you should look to use a database.

Also JSON might be an option aswell. In my opinion the better way.

const germanToEnglisch = {
  word1 = 'Wort1',
  word2 = 'Wort2',
  word3 = 'Wort3'
};

You can now access the word you want to translate with germanToEnglisch[word1] or with germanToEnglisch.word1, both should work. This requires you to have to word implemented in the object above of course. Hope this helps, i am not sure if i understood your question correctly, as for me it is a bit vague :)

Related