1

I have this problem, I want to be able to translate a custom language. But I can't get it to replace all the letters in a sentence. I have tried all I could think of but nothing. I need to be able to check every single letter of the alphabet and be able to translate it.

        function Translate(){
        var string =  document.getElementById("Unseen").value;
        var Translation = string.replace(/ㅏ/g, "A");
        var Translation = string.replace(/Э/g, "E");

        document.getElementById("Translation").innerHTML = Translation;
    }

It works for translating Э into an E but the ㅏ does not work. It doesn't translate to A.

ItzMrBlox
  • 59
  • 4
  • 2
    you should chain the operations, not use the original as input every time. – ASDFGerte Oct 19 '19 at 17:43
  • How would I go about that? – ItzMrBlox Oct 19 '19 at 17:46
  • 1
    `var Translation = document.getElementById("Unseen").value; Translation = Translation.replace(/ㅏ/g, "A"); Translation = Translation.replace(/Э/g, "E");` and use `var` only once per variable. You can also do it in one line, e.g. as `var Translation = document.getElementById("Unseen").value.replace(/ㅏ/g, "A").replace(/Э/g, "E");` – ASDFGerte Oct 19 '19 at 17:48
  • Also, here is an alternative to having tons of `.replace`: `const dict = { ㅏ: "A", Э: "E" }; const regex = new RegExp(\`[${Object.keys(dict).join("")}]\`, "g"); let Translation = document.getElementById("Unseen").value.replace(regex, m => dict[m]);`, then for every new letter you want to replace, you just need to add it to `dict`. – ASDFGerte Oct 19 '19 at 17:57
  • You asked a similar question a few hours ago and deleted it, right? I had prepared this code, maybe it can help you `const unseen = ["ㅏ", "Б", "C", "Δ"]; const normal = ["A", "B", "C", "D"]; const uToN = {}; const nToU = {}; normal.map((normalChar, i) => { const unseenChar = unseen[i]; nToU[normalChar] = unseenChar; uToN[unseenChar] = normalChar; }); function translate(msg) { let out = ''; msg.split('').forEach(char => { if (nToU[char]) { out += nToU[char]; } if (uToN[char]) { out += uToN[char]; } }); return out; }` – Stratubas Oct 19 '19 at 18:03
  • 1
    And one more note, just for completion's sake: For my code above, if you intend to use regexp syntax symbols in the translation `dict`, you'll need to [sanitize it first](https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript), but it doesn't seem like you would, so there is no problem anyways. – ASDFGerte Oct 19 '19 at 18:18

0 Answers0