1

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

1
  • Strings are immutable in JS, so you can only create a new string. // How to get the character at a certain position is something you can research yourself. And then, in your loop you either append the original character or the replacement to your new string. Commented May 19, 2017 at 10:16

5 Answers 5

4

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't it be text.charAt(x) rater than string.charAt(x) ?
You are correct @IggyPass. I've updated the code. Good eye! Thank you!
1

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

Comments

0

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>

Comments

0

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>

Comments

0

use string length and iterate and replace whatever you want.

for(var i=0 ; i < yourstring.length ; i++){
    yourstring= yourstring.replace(yourstring[i],"yourvalue")
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.