Home > Net >  replace handler en masse
replace handler en masse

Time:09-22

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')

CodePudding user response:

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"
}))

  • Related