繁体   English   中英

使用Regex将String替换为具有Array元素的数组索引。 jQuery的

[英]Replace String with array indexes with Array elements using Regex. Jquery

我需要一个字符串助手来用变量替换方括号内的所有内容。 使用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"])

因此,基本上Modify()将采用数组并将字符串替换为适当的索引。

任何意见将是有益的。

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

所有的答案都是有用的,

但是我已经使用了@PedrodelSol提供的链接中的内置功能

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM