Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

243
Views
Vanilla JS - .replace() with array and loop

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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")); 

about 4 years ago · Juan Pablo Isaza Report

0

You could also do this with a switch statement.

switch(wordInEnglish) {

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

    case "Arrow": return "Assan";

}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!