繁体   English   中英

用 JavaScript 在字符串的多个位置的两个给定索引之间替换字符串

[英]String replace between two given indexes in multiple places of the string with JavaScript

我有一个字符串和字符串中的开始和结束索引数组,需要用其他内容替换。 例如,输入字符串如下:

Mention 1, Mention 3 and no more mentions.

而要替换的索引数组如下:

[
  {
     start: 0,
     end: 8
  },
  {
     start: 11;
     end: 18
  }
]

基本上这应该会产生一个字符串,其中Mention 1Mention 3被包裹在一个锚点(链接)中。

我找到了一些这样的例子:

String.prototype.replaceBetween = function(start, end, what) {
  return this.substring(0, start) + what + this.substring(end);
};

console.log("The Hello World Code!".replaceBetween(4, 9, "Hi"));

但是,此实现的问题在于,只有只有 1 个位置可以替换才好,在我的情况下,可以有多个位置可以替换。 在第一次替换之后,rest 的索引将被移动,因为字符串现在也将包含。

任何提示/线索将不胜感激。

编辑:这里有 2 个问题,因为您的示例并没有真正涵盖包装。

正如您提到的,使用索引,每次替换都会在替换移动所有元素的 position。 但是,它之前的字符索引将保持不变。 您只需要反向迭代它们。

var str = 'Mention 1, Mention 3 and no more mentions.'
for (const { start, end } of positions.reverse()) {
  str = str.replaceBetween(start, end, 'REPLACEMENT')
}

不过,这并没有真正解决包装问题。 如果您实际上必须使用数组索引,则可以将上面的内容更改为接受 function,例如:

String.prototype.replaceBetween = function (start, end, replacer) {
  const what = replacer(this.substring(start, end));
  return this.substring(0, start) + what + this.substring(end);
};

for (const { start, end } of positions.reverse()) {
  str = str.replaceBetween(start, end, (match) => `<a href="#">${match}</a>`);
}

但是,如果索引数组只是搜索特定模式的产物,则更简洁的解决方案可以利用String#replace和正则表达式和替换器 function

// the `/g` at the end means "global", so it will replace all matches
const pattern = /Mention \d+/g;

var str = 'Mention 1, Mention 3 and no more mentions.'
str = str.replace(/Mention \d+/g, (match) => {
  return `<a href="#">${match}</a>`;
});

Output: '<a href="#">Mention 1</a>, <a href="#">Mention 3</a> and no more mentions.'

您必须遍历 position 数组。 像那样:

 const n = [ { start: 0, end: 8 }, { start: 11, end: 18 } ]; let str = 'Mention 1, Mention 3 and no more mentions.'; String.prototype.replaceBetween = function(start, end, what) { return this.substring(0, start) + what + this.substring(end); }; n.forEach(e => { console.log("The Hello World Code.".replaceBetween(e,start. e,end; "Hi")); })

暂无
暂无

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

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