0

I need an string helper to replace everything within the square brackets with variables. using javascript

"Hello, [0]".modify(["ABC"])

"Heelo, [0], This is [1]".modify(["ABC", "XYZ"])

"Heelo, [0], This is [1], Your email address is [2]".modify(["ABC", "XYZ", "abcdef@example.com"])

So basically the modify() will take the array and replace the string with appropriate indexs.

Any advice would be helpful.

3 Answers3

0
String.prototype.modify = function(arr) {
    return this.replace(/\[(\d+)\]/g, function(c, m) {
        return arr[m] === undefined ? c : arr[m];
    });
};

"Heelo, [0], This is [1]".modify(["ABC", "XYZ"]);
// "Heelo, ABC, This is XYZ"
VisioN
  • 143,310
  • 32
  • 282
  • 281
0
String.prototype.modify = function() {
  var s = arguments[0];
  for (var i = 0; i < arguments.length - 1; i++) {       
    var reg = new RegExp("\\[" + i + "\\]", "gm");             
    s = s.replace(reg, arguments[i + 1]);
  }
  return s;
}
K D
  • 5,889
  • 1
  • 23
  • 35
0

All the answers were usefull,

But I have used the in-build function, from the link provided by @PedrodelSol

"Hello {0}, This is {1}".format(["ABC", "XYZ"])