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>
3

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

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 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.
ty for answer it did worked perfectly but i needed script with for loop.
@Duke Sure, no problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.