使用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"));

然而,这个实现的问题是,只有当只有一个地方可以替换时,它才是好的,在我的情况下,可以有多个地方可以被替换。在第一次替换之后,其余部分的索引将被移动,因为字符串现在也将包含。

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

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

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

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

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

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>`);
}

不过,如果indexes数组只是搜索特定模式的工件,那么更干净的解决方案可以利用带有regex和replacer函数的String#replace

// 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>`;
});

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

您必须在位置数组上循环。比如:

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

最新更新