• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

222
Views
Replace words from a string from a wordlist in JavaScript

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?

about 3 years ago · Santiago Gelvez
2 answers
Answer question

0

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.

about 3 years ago · Santiago Gelvez Report

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)

about 3 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error