【问题标题】:JS Replace only replacing first pair [duplicate]JS替换仅替换第一对[重复]
【发布时间】:2021-09-03 20:33:53
【问题描述】:

我的代码是:

function fms(e) {
  eq = e
  eq = eq.replace('f(', '<em>f</em>(')
  eq = eq.replace(' / ', ' &#247; ')
  eq = eq.replace('{', '<sup>')
  eq = eq.replace('}', '</sup>')
  return eq
}
a = fms('x{y} x{y}')
console.log(a)

它应该在 {} 中的任何内容周围添加 sup,但是:我的 a 变量只有第一对周围,第二个保持不变:

x<sup>y</sup> x{y}

我很困惑。如果您知道原因,请务必告诉我!

【问题讨论】:

    标签: javascript


    【解决方案1】:

    使用replaceAll 而不是replace,因为您使用的是要被另一个字符串替换的字符串。

    String.prototype.replace()

    replace() 方法返回一个新字符串,其中模式的部分或全部匹配被替换。模式可以是stringRegExp,替换可以是stringfunction,为每次匹配调用。 如果 pattern 是一个字符串,则只替换第一个匹配项。

    Reference

    function fms(e) {
      eq = e
      eq = eq.replaceAll('f(', '<em>f</em>(')
      eq = eq.replaceAll(' / ', ' &#247; ')
      eq = eq.replaceAll('{', '<sup>')
      eq = eq.replaceAll('}', '</sup>')
      return eq
    }
    a = fms('x{y} x{y}');
    console.log(a)

    如何让String.replace 替换所有的出现?

    如果我们使用regex 代替字符串,您可以使用replace 本身替换所有出现的字符串。

    工作示例

    function fms(e) {
      eq = e;
      eq = eq.replace(/f\(/g, '<em>f</em>(')
      eq = eq.replace(/\//g, ' &#247; ')
      eq = eq.replace(/{/g, '<sup>')
      eq = eq.replace(/}/g, '</sup>')
      return eq
    }
    a = fms('x{y} x{y}');
    console.log(a);

    【讨论】:

    • 我格式化了 OP 的问题,所以你比我要答案;)
    猜你喜欢
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 2016-12-15
    相关资源
    最近更新 更多