1

The goal of the swap function is to replace the strings enclosed by {{}} in the class's this.string with the corresponding items in the map that is passed into the swap method.

class Swapper
{
 constructor(arg)
 {
  this.string = arg;
 }

 /*I pass in a map that dictates what to swap*/
 swap(map)
 {
   this.string.replace(/\{\{([^}]+)\}\}/g, (_, i) => map[i]);
 }

}

When I test the class method with:

const item = new Swapper('Hello {{replace1}}! {{replace2}}.');

/*tests*/
console.log(item.string); 
console.log(item.swap({replace1: "World", replace2: "bye"}));

item.swap({replace1: "World", replace2: "bye"});
console.log(item.string);

none of the trys are succesful. Output says:

Hello {{replace1}}! {{replace2}}.
undefined
Hello {{replace1}}! {{replace2}}.

but I want the string to be changed to "Hello World! bye."

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • 3
    `String.prototype.replace()` does not modify the source string; it returns a *new* string. – Pointy Jun 28 '21 at 22:04

1 Answers1

1

Simply reassign again like this.string =

class Swapper {
  constructor(str) {
    this.string = str;
  }
  swap(map) {
    this.string = this.string.replace(/\{\{([^}]+)\}\}/g, (_, i) => map[i]);
  }
}

const item = new Swapper('Hello {{replace1}}! {{replace2}}.');
item.swap({
  replace1: "World",
  replace2: "bye"
});
console.log(item.string);

Not sure what's the assignment, but that code seems quite strange in my subjective opinion. Using a class that modifies a string only once, but it first needs to be instantiated before ultimately call an odd .swap Method which will destroy the placeholders anyways. Why not do it in a single go - without a class, or at least at init?!

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313