簡體   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