How to iterate over a string to create a new string?

Viewed 430

I just want to iterate over "banana" and exchange each letter with "A" to obtain a new string "AAAAAA". Why this code doesn't work?

let word = "banana";
for (letter of word)
 {
  letter = "A";
  return word;
 }
5 Answers

You are actually overwritting the local variable letter once, then you return the unchanged word

If you want to replace all letters by a 'A', you can repeat that letter as much time as the length of the string :

let word = 'banana';

word = 'A'.repeat(word.length);

console.log(word);

Your code isnt working for several reasons: the letter variable you get in the for of loop is only suppose to be a reference you shouldnt change it, also the return statement you setup does nothing you cant return from a for loop. I would do it this way:

let word = "banana"
//We repeat the string "A" by the length of the string
const convertedString = 'A'.repeat(word.length)
console.log(convertedString)

(Edit) Using for of loop:

  let word = "banana";
  let convertedString = "";

  //we set the paramater as _ because we dont need it of course you can change it back to letter
  for (_ of word) {
    //when using the += it means that we do this: convertedString = convertedString + "A"
    convertedString += "A";
  }

  console.log(convertedString);

you can use this :

let word = "banana";
let letters = "";
for (i of word){
    letters += "A"
}

Using a return statement in the for loop, will return directly after the first iteration, and will return the value of variable word which is banana

You could also replace every non whitespace \S char with A

let word = "banana";
console.log(word.replace(/\S/g, 'A'));

Other options could be using split and map:

let word = "banana";
console.log(word.split('').map(_ => 'A').join(''));

Or for example a plain for loop:

let word = "banana";
let letters = '';
for (let i = 0; i < word.length; i++) {
  letters += 'A';
}
console.log(letters);

Related