【问题标题】:Replacing all instances of certain character in JS?替换JS中某个字符的所有实例?
【发布时间】:2017-02-10 15:10:21
【问题描述】:

我正在尝试创建一个简单的函数来替换 JS 中字符串中某个字符的所有实例。在这种情况下,我想用o 替换所有a

我很确定代码是正确的,但输出仍然是原始字符串。

function replaceLetter(string){
  for(var i = 0; i < string.length; i++){
    if(string[i] == 'a'){
      console.log(string[i]);
      string[i] = 'o'
    }
  }
  return string;
}

replaceLetter('hahaha') // returns 'hahaha'

为什么不用o替换a?

【问题讨论】:

标签: javascript iteration


【解决方案1】:

你可以像这样使用正则表达式:

function replaceLetter(str) {
    return str.replace(/a/g, 'o');
}

var st = replaceLetter('hahaha');

console.log(st);

或者使用另一个字符串来累积结果,如下所示:

function replaceLetter(str) {
    var res = '';                               // the accumulator (because string litterals are immutable). It should be initialized to empty string
  
    for(var i = 0; i < str.length; i++) {
        var c = str.charAt(i);                  // get the current character c at index i
        if(c == 'a') res += 'o';                // if the character is 'a' then replace it in res with 'o'
        else res += c;                          // otherwise (if it is not 'a') leave c as it is
    }

    return res;
}

var st = replaceLetter('hahaha');

console.log(st);

【讨论】:

    【解决方案2】:

    我一直喜欢使用split()join()

    var string = "assassination";
    var newString = string.split("a").join("o");
    

    【讨论】:

      【解决方案3】:

      Strings in Javascript are immutable,因此对它们的任何更改都不会像您预期的那样反映。

      考虑只使用string.replace() 函数:

      function replaceLetter(string){
        // This uses a regular expression to replace all 'a' characters with 'o'
        // characters (the /g flag indicates that all should be matched)
        return string.replace(/a/g,'o');
      }
      

      【讨论】:

        【解决方案4】:

        假设您想使用for 循环:

        function replaceLetter(string){
          var result = '';
        
          for (var i = 0; i < string.length; i++) {
            result += string[i] === 'a' ? 'o' : string[i];
          }
          return result;
        }
        

        您必须像这样构建一个新字符串,因为正如评论中提到的,字符串是不可变的。你可以写string[4] = 'b',它不会导致错误,但它也不会做任何事情。

        这可能有点矫枉过正,但您可以使用reduce,它在内部进行循环并维护result 变量:

        const replaceLetter = string => 
          [...string].reduce((result, chr) => 
            result += (chr === 'a' ? 'o' : chr), '');
        

        但是,对于这种特殊情况,其他答案中显示的正则表达式解决方案可能更可取。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-08-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-04
          • 2012-11-14
          • 2014-03-14
          相关资源
          最近更新 更多