Home > other >  Vanilla JS - .replace() with array and loop
Vanilla JS - .replace() with array and loop

Time:12-15

I wrote myself a little script that converts English words to Elvish words.

var clickMe = document.querySelector('#button-7993f34d');

clickMe.addEventListener('click', function (event) {
  setTimeout(function() {
    var checkSelect = document.querySelector("select");
    // Lang
    checkSelect.innerHTML = checkSelect.innerHTML.replace('Tree', 'Adahl');
    checkSelect.innerHTML = checkSelect.innerHTML.replace('Forest', 'Adahlen');
    checkSelect.innerHTML = checkSelect.innerHTML.replace('Arrow', 'Assan');
  }, 0);
});
<select>
  <option>Tree</option>
  <option>Forest</option>
  <option>Arrow</option>
</select>
<button id="button-7993f34d">click me</button>

Everything works fine. However, I would like to present the words in the form of an array. For example:

langs = [
  {"eng": "Tree", "elf": "Adahl"},
  {"eng": "Forest", "elf": "Adahlen"},
  {"eng": "Arrow", "elf": "Assan"}
]

And not repeat it:

 checkSelect.innerHTML = checkSelect.innerHTML.replace('Tree', 'Adahl');

This thread was closest to my solution: Using replace string method inside forEach However, I was unable to adapt it to my script.

Is it possible in my case? I tried to find a similar solution with the replace function. Unfortunately, to no avail. Can you advise something?

Still, I keep trying, if I find a solution before answering, I will definitely share it.

CodePudding user response:

Here is a very basic function that replaces occurrences of your english terms with elvish terms.

function replaceText(text) {
  const langs = [
    {"eng": "Tree", "elf": "Adahl"},
    {"eng": "Forest", "elf": "Adahlen"},
    {"eng": "Arrow", "elf": "Assan"}
  ];
  let textToReturn = text;
  langs.forEach((word) => {
    textToReturn = textToReturn.replaceAll(word.eng, word.elf);
  });
  return textToReturn;
};

console.log(replaceText("My Tree is in the Forest")); 

CodePudding user response:

You could also do this with a switch statement.

switch(wordInEnglish) {

    case "Tree": return "Adahl";
    
    case "Forrest": return "Adahlen";

    case "Arrow": return "Assan";

}
  • Related