1

I want to do it like I give a list of words and a meaning to them e.x.:

'szia' = 'hello' 'mizu' = 'whats up'

and then I have a string that goes like this: var string = "szia mizu". How can I replace the words there from the list?

deth1169
  • 37
  • 1
  • 2
  • Does this answer your question? [How to replace all occurrences of a string in JavaScript](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – Rafał Figura Apr 12 '22 at 19:07
  • no it does not anwser my questiuon – deth1169 Apr 12 '22 at 19:08
  • you could have a dictionary holding the translations. then you can use split method on your string and for each word look up the translation in the dictionary. – coglialoro Apr 12 '22 at 19:11

2 Answers2

1

let sentence = "szia mizu";

const traduction= {
  "hello": ['szia'],
  "whats up": ['mizu']
};

function fileAndReplace(sentence, traduction) {
  let newSentence = sentence;
    
  Object.keys(traduction).forEach(key => {
      const checktrad = new RegExp(traduction[key].join('|'),'gi');
      newSentence = newSentence.replace(checktrad , key);
  })
     
  return newSentence;
}

console.log(fileAndReplace(sentence, traduction))

you need to iterate through all the keys in your dictionary and create a regex for that specific key. Then you just feed that regex to the .replace() with the synonym regex and the key you want to replace it with.

0

You can archive this with js replace() function:

const needles = {
  szia: "hello",
  mizu: "whats up"
};

let str = "szia mizu";

Object.keys(needles).forEach(n => {
  str = str.replace(n, needles[n]);  
})

console.log(str)
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79