Home > Blockchain >  How to return two or more conditional in javascript?
How to return two or more conditional in javascript?

Time:11-21

Here I want to make a simple translator. I want to make a translator that translates the sentence directly. I use this code as an example. But this only works to translate a word. If you combine two words or more, it can't appear with two words of translation directly. How can I make the code show more words in one frame?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TRANSLATOR</title>
    <style>
        body, input {
            font-size: 20;
        }
        body {
            text-align: center;
        }
    </style>
    <script>
        function checkForTranslation(){
            var input = document.getElementById("inputTextField").value;
            var outputDiv = document.getElementById("translationOutputDiv");
            input = input.toLowerCase();
            if (input == "i") return outputDiv.innerHTML = "aku";
            if (input == "love") return outputDiv.innerHTML = "cinta";
            if (input == "you") return outputDiv.innerHTML = "kamu";
        }
    </script>
</head>
<body>
    <h2>TRANSLATOR</h2>
    <input placeholder="Masukkan kalimat" id="inputTextField" type="text" onkeyup="checkForTranslation()">
    <div id="translationOutputDiv" style="display: inline">[translation]</div>
</body>
</html>

If you try it, then if you input "i", then it will show "aku", but you won't get translation "aku cinta", if you input "i love". That's all i want to solve.

CodePudding user response:

A naïve approach, ignoring the complex differences in linguistics between languages, would be to split your input into an array of words, and modify your translator to use parameters to accept a word and return a translation.

    function translateWord(input){
        if (input == "i") return "aku";
        if (input == "love") return "cinta";
        if (input == "you") return "kamu";
        return input;
    }

    function checkForTranslation(){
        var inputs = document.getElementById("inputTextField").value.split(/\s /);
        var outputDiv = document.getElementById("translationOutputDiv");
        for (let i=0; i<inputs.length; i  ) {
            inputs[i]=translateWord(inputs[i].toLowerCase());
        }
        outputDiv.innerHTML = inputs.join(' ');
    }
  • Related