3

I have this string in an input variable like this: var input = "javascript";

i want to change this string to "j4v4sr1pt" by replacing a with 4 and i with 1.

i tried to do something like this but didn't work for me , i am new to JavaScript .can someone tell me what i am doing wrong here ? THanks for down votes in advance :D

<script>
var input = "javascript";
var output= "";

for ( var i=0;i<input.length ; i++)
   { if ( input[i] == "a")
       {output[i] = "4"; }
     else if ( input[i] == "i")
     {  output[i] ="1"; }
     else
       output[i]=input[i];
    }// end forloop
</script>
Duke
  • 33
  • 1
  • 4
  • `output = input.replace(/a/g, '4')` etc ? – adeneo Oct 10 '15 at 15:19
  • Please check out my answer, and if it works for you, please click the tick under it. – Jacques Marais Oct 10 '15 at 15:24
  • 2
    Does this answer your question? [How do I replace a character at a particular index in JavaScript?](https://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript) and [Replace multiple characters in one replace call](https://stackoverflow.com/questions/16576983/replace-multiple-characters-in-one-replace-call) – ggorlen Jul 25 '21 at 22:23

2 Answers2

4

In JavaScript, strings are immutable, meaning that they cannot be changed in place. Even though you can read each character of a string, you cannot write to it.

You can solve the problem with a regular expression replace:

output = input.replace(/a/g, '4').replace(/i/g, '1');

Or you can solve it by changing output from a string to an array, and then joining it to make it a string:

var input = "javascript";
var output = [];           //change this

for (var i = 0; i < input.length; i++) {
  if (input[i] == "a") {
    output[i] = "4";
  } else if (input[i] == "i") {
    output[i] = "1";
  } else
    output[i] = input[i];
} // end forloop

output= output.join('');   //change array to string
console.log(output);
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79
3

Try the .replace() method like following:

<script>
    var input = "javascript";
    var output = input.replace("a", "4", "g").replace("i", "1", "g");
</script>

Edit: Added g flag to the replace method to replace all matches and not just the first one.

Jacques Marais
  • 2,666
  • 14
  • 33
  • Thanks for the answer , when i run this code output is: j4vascr1pt instead of j4v4sc1pt, its not changing the 2nd 'a' character , can you please tell me why is it so ? – Duke Oct 10 '15 at 15:32
  • @Duke I updated the post, it should work now. I added a `g` flag at the end. The `g` flag means it is global which means it will replace all and not just the first one. – Jacques Marais Oct 10 '15 at 15:39
  • ty for answer it did worked perfectly but i needed script with for loop. – Duke Oct 10 '15 at 15:44
  • @Duke Sure, no problem. – Jacques Marais Oct 10 '15 at 15:49