0

here is my code

</script>
  function myFunction() {
   var a = ["a.m.","p.m","u.k."];
   var b = ["its_morning","its_noon","unKnown_thing"];
   var str = document.getElementById("textBox1").value;
      for (var k = 0; k < a.length; k++) {
        str = str.replace(a[k], b[k]); 
                                         };
   document.getElementById('textBox2').value = str;
     }
</script>

<body>

  <textarea onkeyup="myFunction();"id="textBox1"></textarea>
  <TEXTAREA type="text" id="textBox2"></TEXTAREA>
</body>

when i type 'a.m.' its working fine but when i type it again its not changing . like:

'a.m. hello world a.m.'

gives results

'its_morning hello world a.m.'

here the last 'a.m.' must be replaced but i dont know wats wrong with it

please answer in javascript ,im not familiar with jquery.

Nakul
  • 55
  • 8

2 Answers2

2

The problem is that the replace will not replaceAll automatically. You have to use global regex for this.

eg instead of writing

string.replace("search","replace")

write:

string.replace(/search/g,"replace")

The /g flags means searching globally, eg replaceAll

In your case, I would write the a array as an array of regexes instead:

var a = [ /a\.m\./g, /p\.m/g, /u\.k\./g ];

However, you need to escape special characters, like .

Your code should than be:

<script>
  function myFunction() {
   var a = [
      /a\.m\./g,
      /p\.m/g,
      /u\.k\./g
   ];
   var b = ["its_morning","its_noon","unKnown_thing"];
   var str = document.getElementById("textBox1").value;
      for (var k = 0; k < a.length; k++) {
        str = str.replace(a[k], b[k]); 
                                         };
   document.getElementById('textBox2').value = str;
     }
</script>
edi9999
  • 19,701
  • 13
  • 88
  • 127
-2

String.replace(String, String) just replaces the first occurence.

You can use the regex with "g" modifier so it replaces every occurence. Since, it is dynamic string, you should use RegExp constructor.

str = str.replace(new RegExp(a[k].replace(/\./g, '\\.'),"g"), b[k]); 
Amit Joki
  • 58,320
  • 7
  • 77
  • 95