【问题标题】:Replace all occurrences of substring with values from array [duplicate]用数组中的值替换所有出现的子字符串[重复]
【发布时间】:2020-01-07 19:13:32
【问题描述】:

我有两个数组。一个数组包含要搜索的字符,另一个数组包含要替换它们的字符。我想在一个字符串中查找第一个数组中每个项目的所有出现,并将它们替换为第二个数组中对应的项目。

let converted = '';
    let bbCodes = [
      "[code]", "[/code]", "[h1]", "[/h1]"
    ];
    let replacers = [
      "<code>", "</code>", "<h1>", "</h1>"
    ];
    let needsConverted = this.state.txtAreaVal;
    bbCodes.map((code, index) => {
        converted = needsConverted.replace(code, replacers[index]);
        console.log(converted);
    });
    console.log(converted);
  }

输出并不完全符合我的预期。

【问题讨论】:

标签: javascript arrays


【解决方案1】:

问题是您没有跟踪字符串的已更新版本。

  • 在第一次迭代时,它会替换第一个单词([code]&lt;code&gt;)。然后将此值分配给converted

  • 在第二次迭代中,您替换 original 字符串的第二个单词并将结果分配给 converted,从而失去上一次迭代的更改。

您不需要其他变量,您可以重复使用初始字符串并在每次迭代时不断替换它。

另外,您可以使用forEach,而不是使用map,这更合适,因为您不会更改数组中的值。

let bbCodes = [
  "[code]", "[/code]", "[h1]", "[/h1]"
];
let replacers = [
  "<code>", "</code>", "<h1>", "</h1>"
];
let needsConverted = 'this is a [code] code [/code] test see [h1] here [/h1]';
bbCodes.forEach((code, index) => {
    // you don't need your other function, you can just reassign your current string to it's new value.
    needsConverted = needsConverted.replace(code, replacers[index]);
});
console.log(needsConverted);

【讨论】:

  • 完美。我知道我遗漏了一些小细节。我最初使用 forEach,切换到地图并没有多大意义哈哈。
【解决方案2】:

我假设,您正在努力实现这一目标:

let converted = '';
let bbCodes = [
  "[code]", "[/code]", "[h1]", "[/h1]"
];
let replacers = [
  "<code>", "</code>", "<h1>", "</h1>"
];
let needsConverted = 'Lorem ipsum is [h1]dummy text[/h1] in the industry.';
bbCodes.map((code, index) => {
  needsConverted = needsConverted.replace(code, replacers[index]);
  console.log(needsConverted);  
});

您的基本实现没问题。但是,您将替换的结果分配给了一个新变量。因此,您总是只替换最初输入的字符串中的一个标记。如果您将其重新分配给初始输入变量,您的结果将是替换了数组中所有给定标记的字符串。

重要的变化是

let converted = needsConverted.replace(code, replacers[index]);

改为

needsConverted = needsConverted.replace(code, replacers[index]);

【讨论】:

    猜你喜欢
    • 2013-04-15
    • 2017-03-20
    • 2012-08-01
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多