Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

replace handler en masse

Hello, How to work with replace in bulk
I want to replace in bulk, and not to take up too much code
Look at how I do it:

    const t1 = service.replace[
        'SERVICE=1', 'test1',
        'SERVICE=3', 'test2',
        'SERVICE=2', 'test3'
    ]
    // const t = service
    // .replace('SERVICE=1', 'test1')
    // .replace('SERVICE=2', 'test3')
    // .replace('SERVICE=3', 'test2')

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can create a little function. Please note it replaces only first occurrence of each string. Also, pay attention of passing the longer strings first, so to prevent side effects of replacing strings that contained in other strings.

function replacer(str, data) {
  if (typeof data === 'object' && str) {
    for (var key in data) {
      var value = data[key];
      str = str.replace(key, value);
    }
  }
  return str;
}

console.log(replacer("goodbye galaxy", {
  "goodbye": "hello",
  "galaxy": "world"
}))

// stay tuned for a prototype of String
String.prototype.replacer = function(data) {
  return replacer(this, data);
};
console.log("goodbye galaxy".replacer({
  "goodbye": "hello",
  "galaxy": "world"
}))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading