Home > Software design >  Replace words from a string from a wordlist in JavaScript
Replace words from a string from a wordlist in JavaScript

Time:04-13

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?

CodePudding user response:

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.

CodePudding user response:

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)

  • Related