How can I iterate over the characters in a string, and change them?

I want to take a string, and change each character. I.e. A becomes E or F becomes C.

what I have is this:

function convert(){
  var text=document.getElementById('textInp').value;
  alert(text);
  for()
}

I don’t know what to do in the for loop

5 thoughts on “How can I iterate over the characters in a string, and change them?”

  1. use string length and iterate and replace whatever you want.

    for(let i = 0; i < yourstring.length; i++) {
        yourstring = yourstring.replace(yourstring[i],"yourvalue");
    }
    
    Reply
  2. Try this split("") split the string with space .and match the letter then replace using map

    function convert(){
      var text=document.getElementById('textInp').value;
     console.log(text.split("").map(a=> a= a.toUpperCase() == 'A'? 'E':a.toUpperCase() == 'F'?'C':a ).join(""))
    }
    <input id="textInp" value="AonFncdcd">
    <button onclick="convert()">click</button>
    Reply
  3. You can split and join your String

    function convert(){
       var text = document.getElementById('textInp').value;
       alert(text);
       text = text.split('A').join('E').split("F").join("C");
    }
    
    Reply
  4. There is a direct option to iterate over a string directly: to use for...of or for...in:

    function convert(){
      let text = document.getElementById('textInp').value;
      for(let i in text) {
        // Do something
        console.info('i:', i, ' char: ', text[i])
      }
    }
    <input id="textInp" value="Your input">
    <button onclick="convert()">click</button>
    Reply
  5. You can iterate over each of the characters in the text like this

    for (var x = 0; x < text.length; x++)
    {
        var c = text.charAt(x);
        //Add code here to do the translation
    }
    
    Reply

Leave a Comment