1

I want to replace some words in string. I have got working solution but I don't think it's the best one. Could you please help me with more effective & clever solution (less code)?

The code is avaiable live here: https://codepen.io/yasAFE/pen/BYOVme

function main() {
      var input = document.getElementById("input");
      var output = input.value.replace(/red/gi, "blue") // how to write this but 
                          .replace(/bad/gi, "good")  // with less code?
                          .replace(/girl/gi, "boy")
                          .replace(/gold/gi, "metal"); 
  input.value = output;
}
<textarea id="input" spellcheck="false" autocorrect="off"></textarea>
<button class="button" onclick="main()">Transform my text</button>
ricky
  • 1,644
  • 1
  • 13
  • 25
krkoska
  • 71
  • 2
  • 6

1 Answers1

0

You can use a function like this:

var mapObj = {
     cat:"dog",
     dog:"goat",
     goat:"cat"
};

var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
str = str.replace(re, function(matched){
  return mapObj[matched];
});
danilonet
  • 1,757
  • 16
  • 33
  • 3
    instead of copying answer from some other question, you can refer the question in the comment itself. https://stackoverflow.com/questions/15604140/replace-multiple-strings-with-multiple-other-strings – Suresh Ponnukalai Feb 26 '18 at 11:38