admin管理员组

文章数量:1420981

I am trying to create a simple function that replaces all instances of a certain character in a string in JS. In this instance, I want to replace all a's with o's.

I am pretty sure the code is right, but the output is still the original string.

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'

Why isn't it replacing a's with o's?

I am trying to create a simple function that replaces all instances of a certain character in a string in JS. In this instance, I want to replace all a's with o's.

I am pretty sure the code is right, but the output is still the original string.

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'

Why isn't it replacing a's with o's?

Share Improve this question asked Feb 10, 2017 at 15:10 IggyIggy 5,27112 gold badges59 silver badges97 bronze badges 3
  • 1 Strings are immutable -> String.prototype.replace() – Andreas Commented Feb 10, 2017 at 15:12
  • Is this an algorithm design exercise, or is the goal actually to do sub-string replacement? – msanford Commented Feb 10, 2017 at 15:13
  • Possible duplicate of Fastest method to replace all instances of a character in a string – Abdennour TOUMI Commented Feb 14, 2017 at 3:31
Add a ment  | 

4 Answers 4

Reset to default 3

You can use a regular expression like this:

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

var st = replaceLetter('hahaha');

console.log(st);

Or use another string to accumulate the result like this:

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);

I always like using split() and join()

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

Strings in Javascript are immutable, and thus any changes to them aren't going to be reflected as you might expect.

Consider just using the string.replace() function instead:

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');
}

Assuming you want to use a for loop:

function replaceLetter(string){
  var result = '';

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

You have to build a new string like this, because as mentioned in a ment, strings are immutable. You can write string[4] = 'b' and it won't cause an error, but it won't do anything either.

It's probably overkill, but you could use reduce, which does the looping internally and maintains the result variable:

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

However, for this particular case, the regexp solution shown in other answers is probably preferable.

本文标签: javascriptReplacing all instances of certain character in JSStack Overflow