【问题标题】:Failing to replace characters of a string inside a for loop无法在 for 循环中替换字符串的字符
【发布时间】:2021-01-23 14:08:28
【问题描述】:

我的代码是这样的..

function replaceAll(str, from, to) {
  let result = ''
  for(let i = 0 ; i < str.length ; i++) 
  if(str[i]===from) {
       result = str.replace(from,to) 
     }
   }
   return result; 
 }

我想就这样回来

let output = replaceAll('loop', 'o', 'e');
console.log(output); // --> 'leep'

但它只是改变了'leop'

【问题讨论】:

  • 很不清楚,为什么你需要一个循环。
  • @NinaScholz 来处理 replace(string, ...) 仅替换该字符串的第一次出现的事实。但是整个构造很麻烦,只有from.length === 1

标签: javascript replace


【解决方案1】:

您可以通过两种方式解决您的问题:

  • 使用replace函数(每个浏览器都支持)和全局修饰符(/…/g)替换所有出现的地方
  • 使用replaceAll 函数(Chrome 85+、Edge 85+、Firefox 77+、Opera 71+、Safari 13.1+ 支持;Internet Explorer 不支持)

let str = 'loop';
console.log(str.replace(/o/g, 'e'));
console.log(str.replaceAll('o', 'e'));

【讨论】:

    【解决方案2】:

    您可以在 JavaScript 中使用replaceAll() 函数。

    const str = 'loop';
    console.log(str.replaceAll('o', 'e'));

    【讨论】:

    • 其实我是用loop来学习的,但是真的很简单!。好的,我会考虑:)
    【解决方案3】:

    为什么?

    对于简单替换,只替换第一个匹配的文本。所以你需要使用g-全局文本匹配模式。但是您从文本作为变量传递。所以使用RegExp 创建正则表达式,如

    RegExp(from,'g')

    function replaceAll(str, from, to) {
      return str.replace(RegExp(from,'g'),to)
    }
    
    let output = replaceAll('loop', 'o', 'e');
    console.log(output); // --> 'leep'

    【讨论】:

    【解决方案4】:

    它告诉你为什么它不起作用。

    function replaceAll(str, from, to) {
                let result = str;
                for(let i = 0 ; i < str.length ; i++) {
                    if(str[i]===from) {
                        result = result.replace(from,to);
                    }
                }
                return result; 
            }
    

    【讨论】:

      【解决方案5】:

      如果你真的想进行循环,你需要将替换后的字符串分配给str而不是结果,因为你将原来的str用于替换,但分配给result

      String#replace 仅替换字符串的第一个查找。如果你采用正则表达式,你可以直接替换所有出现的地方。

      function replaceAll(str, from, to) {
        for (let i = 0; i < str.length; i++) {
          if (str[i] === from) {
            str = str.replace(from, to);
          }
        }
        return str;
      }
      
      
      let output = replaceAll('loop', 'o', 'e');
      console.log(output); // --> 'leep'

      【讨论】:

      • 哇.. 有趣然后 str 没有改变?
      • str 是一个局部变量,由于传递了一个原语,像一个字符串,你需要给这个字符串赋值。
      【解决方案6】:

      让我们深入研究您的问题,以便您了解这里的实际情况


      function replaceAll(str, from, to) {
            let result = ''
                for(let i = 0 ; i < str.length ; i++) 
                    if(str[i]===from) {
                        result = str.replace(from,to) 
                    }
                }
            return result; 
      }
      

      str 是一个字符串类型的变量。字符串数据类型是值类型。当您更改字符串中的字符时,它不会重写初始变量的内容。而是创建一个新的字符串值并将其存储到内存中。以前的值是垃圾收集的。

      最初是str == loop,现在如果您先将'o' 更改为'e',那么str 仍然是“循环”。一个新数据分配给result 变量,该变量保存值'leop'。这就是为什么在你的 for 循环中总是将相同的值分配给结果变量。

      让我们可视化这个过程:


      1st iteration : 
        result = 'loop'.replace('o','e') // leop
        // result is now 'leop' and str remains 'loop'
      
      2nd iteration :
        result = 'loop'.replace('o','e') // leop
       // as str remained 'loop', so result will again be 'leop
      

      这就是为什么 result 变量在 for 循环完成后保持不变的原因。


      另外需要注意的是,虽然在第一次和第二次迭代中,result 变量的值是相同的 ('leop'),但是在第二次循环中,第一个循环的初始 'leop'gurbage collected (thrown away) 以便分配它另一个值(在我们的例子中是另一个 'leop'

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-07
        • 1970-01-01
        • 1970-01-01
        • 2020-10-16
        • 1970-01-01
        • 2014-12-14
        • 2015-01-17
        • 2011-02-05
        相关资源
        最近更新 更多